Move object to mouse position
I have this script that moves a target object to the position on the field, where the mouse is pointing. The problem is that the camera angle is tilted down, so when the target object moves away from the camera, it changes it's height.
That is what I mean. Notice the different y value: ][1]
Script:
var speed:float;
var start : Vector3;
var pos : Vector3;
function Start()
{
start = transform.position;
pos = transform.position;
}
function Update ()
{
//transform.position.y = 0; //This doesn't work apparently :(
pos = Input.mousePosition;
pos.z = 45;
pos = Camera.main.ScreenToWorldPoint(pos);
transform.position = Vector3.Lerp(transform.position, pos, speed*Time.deltaTime);
}
Answer by b1gry4n · Oct 13, 2016 at 03:27 PM
ScreenToWorldPoint translates the mouse position into world space relative too the camera. I think the functionality you want would be a ray from the mouse position
//the object to move
public Transform moveThis;
//the layers the ray can hit
public LayerMask hitLayers;
void Update()
{
Vector3 mouse = Input.mousePosition;
Ray castPoint = Camera.main.ScreenPointToRay(mouse);
RaycastHit hit;
if (Physics.Raycast(castPoint, out hit, Mathf.Infinity, hitLayers))
{
moveThis.transform.position = hit.point;
}
}
Your answer
Follow this Question
Related Questions
Can't call raycast on plane to get mouse position? Beginner Question 1 Answer
2.5D look at mouse 1 Answer
How to check if a player click on a object: Android Mobile 1 Answer
[2D] Raycast points to 0,0,0 instead of mouse... 1 Answer
Getting mouseposition outside of Editor Window in Scene View 1 Answer