Skip to content

Instantly share code, notes, and snippets.

@romainPechot
Created May 6, 2015 13:10
Show Gist options
  • Save romainPechot/3cb4937a693bd7cc8ec5 to your computer and use it in GitHub Desktop.
Save romainPechot/3cb4937a693bd7cc8ec5 to your computer and use it in GitHub Desktop.
Move Gameobject with mouse click relative to camera.
using UnityEngine;
using System.Collections;
public class MouseClickPosition : MonoBehaviour
{
public Camera cam;
public Transform target;
public bool useRaycast = false;
public LayerMask maskFilter;
private RaycastHit hit;
public float distanceToCamera = 10f;
private void Update()
{
if(Input.GetMouseButtonDown(0))
{
if(useRaycast)
{
// hit ?
if(Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit, distanceToCamera, maskFilter))
{
// move to position
target.position = hit.point;
}
}
else
{
// move to position
target.position = cam.ScreenToWorldPoint(Input.mousePosition + Vector3.forward * distanceToCamera);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment