Skip to content

Instantly share code, notes, and snippets.

@pctroll
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pctroll/bc89e177f025e291731a to your computer and use it in GitHub Desktop.
Save pctroll/bc89e177f025e291731a to your computer and use it in GitHub Desktop.
Example Raycast with mouse click
using UnityEngine;
using System.Collections;
public class AiMscCrosshair : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) {
Vector3 newPosition = GetScreenToWorldPos(Input.mousePosition);
newPosition.y = gameObject.transform.position.y;
GameObject newObj = Instantiate(prefabRef, newPosition, new Quaternion()) as GameObject;
}
}
Vector3 GetScreenToWorldPos (Vector3 mousePosition) {
// this is just an example, be careful
// anyways, this is more or less the way I do things so I can reuse code
Ray ray = Camera.main.ScreenPointToRay(mousePosition);
// I create an auxiliar temporal plane so the ray can get the position at y-axis 0.0f
Plane plane = new Plane(Vector2.up, Vector3.zero);
float distance = 0;
if (plane.Raycast(ray, out distance)) {
return ray.GetPoint(distance);
}
return Vector3.zero;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment