Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Last active January 5, 2021 18:37
Show Gist options
  • Save unitycoder/942c8bec545d626743fc4342d7fa6664 to your computer and use it in GitHub Desktop.
Save unitycoder/942c8bec545d626743fc4342d7fa6664 to your computer and use it in GitHub Desktop.
Texture Pixels to World Position (horizontal plane) and World To Pixel Position (without raycasthit texcoord)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pixel2World : MonoBehaviour
{
public Transform worldObject;
void Update()
{
// pixel to world
int x = 128;
int y = 128;
int texWidth = 256;
int texHeight = 256;
var pixelPos = new Vector2(x, y);
float planeWidth = transform.GetComponent<Renderer>().bounds.size.x;
float planeHeight = transform.GetComponent<Renderer>().bounds.size.z;
float localX = ((pixelPos.x / texWidth) - 0.5f) * planeWidth;
float localY = ((pixelPos.y / texHeight) - 0.5f) * planeHeight;
Vector3 worldPos = transform.TransformPoint(new Vector3(localX, 0, localY));
Debug.DrawRay(worldPos, Vector3.up * 5, Color.red);
// world to pixel
var tex = new Texture2D(texWidth, texHeight, TextureFormat.ARGB32, false);
tex.filterMode = FilterMode.Point;
transform.GetComponent<Renderer>().material.mainTexture = tex;
float wLocalX = texWidth-(((worldObject.position.x) / ((float)planeWidth) * (float)texWidth) + texWidth * 0.5f);
float wLocaly = texHeight-(((worldObject.position.z) / ((float)planeHeight) * (float)texHeight) + texHeight * 0.5f);
tex.SetPixel((int)wLocalX, (int)wLocaly, Color.red);
tex.Apply(false);
}
}
@unitycoder
Copy link
Author

// Given a (u,v) coordinate that defines a 2D local position inside a planar quadrilateral, find the
// absolute 3D (x,y,z) coordinate at that location.
//
// 0 <----u----> 1
// a ----------- b 0
// | | /|
// | | |
// | | v
// | *(u,v) | |
// | | |/
// d------------ c 1
//
// a, b, c, and d are the vertices of the quadrilateral. They are assumed to exist in the
// same plane in 3D space, but this function will allow for some non-planar error.
//
// Variables u and v are the two-dimensional local coordinates inside the quadrilateral.
// To find a point that is inside the quadrilateral, both u and v must be between 0 and 1 inclusive.
// For example, if you send this function u=0, v=0, then it will return coordinate "a".
// Similarly, coordinate u=1, v=1 will return vector "c". Any values between 0 and 1
// will return a coordinate that is bi-linearly interpolated between the four vertices.

public Vector3 QuadLerp(Vector3 a, Vector3 b, Vector3 c, Vector3 d, float u, float v)
{
Vector3 abu = Vector3.Lerp(a, b, u);
Vector3 dcu = Vector3.Lerp(d, c, u);
return Vector3.Lerp(abu, dcu, v);
}

https://forum.unity.com/threads/vector-bilinear-interpolation-of-a-square-grid.205644/#post-1389342

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment