- Home /
Move object to mouse click position
Hey folks,
So I've had some time away from Unity and I've come back to make quite a simple script but I keep getting tripping over my own code.
So basically I've got a couple of things going only, firstly I've got a Character object, nested within it I've got the main camera and also an object to hold the character model.
Outside of the Character object I've got an Empty Game Object called target.
Here's what I want to do, wherever the player clicks the target object moves instantly to that position.
Now I've tried placing a simple script on the target object but it doesn't appear to work.
using UnityEngine;
using System.Collections;
public class targetmove : MonoBehaviour {
// Use this for initialization
void Start () {
Vector3 newPosition = transform.position;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Mouse0))
{
if (Input.GetMouseButtonDown(0))
{
newPosition.x = Input.mousePosition.x;
newPosition.y = Input.mousePosition.y;
transform.position = newPosition;
}
}
}
}
I know that ray casting may be a way to go but I've not used it that much and also when I tried it I had problems as my camera is nested within my character.
Answer by Ilgiz · Aug 19, 2014 at 11:38 AM
maybe it's
using UnityEngine;
using System.Collections;
public class targetmove : MonoBehaviour
{
Vector3 newPosition;
void Start () {
newPosition = transform.position;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
newPosition = hit.point;
transform.position = newPosition;
}
}
}
}
For me this script is just kind of teleporting the object to the clicked position. How can i make the object kind of move to the clicked position?
Answer by falconer · Oct 22, 2014 at 05:51 AM
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
Your answer
