Skip to content

Instantly share code, notes, and snippets.

@gzuidhof
Created October 14, 2014 21:15
Show Gist options
  • Save gzuidhof/0f92f1ecd5789d239279 to your computer and use it in GitHub Desktop.
Save gzuidhof/0f92f1ecd5789d239279 to your computer and use it in GitHub Desktop.
Unity3D 2D Raycasting
public Plane gamePlane;
// Use this for initialization
void Start () {
gamePlane = new Plane(Vector3.zero, Vector3.up, Vector3.right);
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.Mouse0))
{
//Raycast to see if colliders are hit.
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.zero);
if (hit.collider) //Something was hit
{
GameObject hitGameObject = hit.collider.gameObject;
}
//Raycast to get point on 2d plane (to move object there for instance)
//Raycast into plane that makes up platter that all the sprites are on
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float dist; //Distance of camera to intersection of plane.
if (solarPlane.Raycast(ray, out dist)) //If
{
Vector3 rayIntersect = ray.GetPoint(dist);
//Move object that is held, maybe determine delta (save last frame's raycast position).
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment