Last active
August 29, 2015 14:02
-
-
Save pctroll/bc89e177f025e291731a to your computer and use it in GitHub Desktop.
Example Raycast with mouse click
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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