So I’ve searched and searched, and couldn’t find an answer to my question (yes, I searched here too).
So what I want, is after a right mouseclick, a gameobject will move to where the mouse clicked.
My problem is, when I click somewhere on the terrain, the object moves to 0,0,0, and not to where the mouse clicked.
Here is the code
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour
{
public Vector3 startPoint;
private float startTime;
private Vector3 clickedPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
// Use this for initialization
void Start ()
{
startPoint = transform.position;
startTime = Time.time;
}
// Update is called once per frame
void Update ()
{
if(Input.GetMouseButtonDown(1))
transform.position = Vector3.Lerp(startPoint, clickedPosition, (Time.time-startTime)/1.0f);
}
}
It does save the startPoint, but clickedPosition is 0,0,0 no matter what I do. Help will be rewarded with valour.
You can cast a ray from the mouse position and move it to a point wherever the ray intersects something, using Physics.Raycast. Here is some example code:
Ray ray = this.camera.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
RaycastHit hit;
Debug.Log("Casting ray");
if (Physics.Raycast(ray, out hit, 3000))
{
Debug.Log("Ray hit something");
if (hit.collider.gameObject.tag == "Terrain")
{
Vector3 clickedPosition = hit.point;
transform.position = Vector3.Lerp(startPoint, clickedPosition, (Time.time - startTime) / 1.0f);
}
}
This should work, regardless of the screen origin, as you are essentially only working with variables in the 3D environment. Note the additional check to move the object, only if the ray cast from the mouse has hit something … in this case that would be a gameobject with the user-assigned Tag “Terrain”. Hope this helps.
search for raycasting! Basicaly, you need to cast a ray from the mouse’s ScreenToWorldPoint and get the intersection between the ray and the terrain. This is the position you want your object to move to… There are plenty of examples around!
In the code sample you provided, your clickedPosition is initialized at the instantiation of the GameObject. However, at that time, the mousePosition is unknown. You should recapture the mousePosition in the update loop after you check if the mouse button has been pressed.
This is pretty simple. You can use the Vector3.Lerp function to achieve this. Use raycasting to get the mouse click position or the touch position. Then use the initial and the final position in the lerp function. The initial position being the position that the gameobject is at now and the final position being the click / touch position.
You can find the article by The Game Contriver on the same here