I’m looking to translate an object to a mouse click, but do so so the object actually travels to the click instead of “snapping” to the mouse click.
I am trying to use the function “Vector3.MoveTowards()” to accomplish this, but to no avail. What am I doing wrong? (Code Below)
Other info:
-
Game world is a birds-eye camera, Cube with dimensions (200,2,200) and a Sphere called “Player” with (10,10,10) dimensions
-
The Player Object has a RigidBody attached
-
I have tried variations of ordering my MoveTowards function, and also tried Lerp and Slerp
using UnityEngine;
using System.Collections;
public class MoveToClick : MonoBehaviour {
GameObject player;
RaycastHit hit;
Vector3 playerPos = new Vector3 (0,5,0);
float speed;
// Use this for initialization
void Start () {
player = GameObject.Find("Player");
player.transform.position = playerPos;
speed = 100.0f;
hit = new RaycastHit();
//speed = speed * Time.deltaTime;
}
//Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Mouse0)) {
if (Input.GetMouseButtonDown(0)) {
movePlayer();
}
}
}
void movePlayer(){
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 1000.0f)) {
print(playerPos + " " + hit.point + " " + speed);
transform.position = Vector3.MoveTowards(hit.point, playerPos, speed);
}
}
}
2 mistakes here:
-
You are only moving your character when you press your key. How can you get animation then? When you press youre key, you should store the value he has to walk to (Vector3). You have to animate it every frame (or until he reaches that spot).
-
Vector3.MoveTowards has 3 parameters. StartPosition, EndPosition, and a float, that says where you should be between those 2 points.
If last parameter is 0: You will be in start position;
If last parameter is .5f: You will be in the middle of 2 positions;
If last parameter is 1: You will be on end position;
using UnityEngine;
using System.Collections;
public class MoveToClick : MonoBehaviour {
GameObject player;
RaycastHit hit;
Vector3 playerPos = new Vector3 (0,5,0);
float speed;
Vector3 previousPosition;
Vector3 targetPosition;
float lerpMoving;
// Use this for initialization
void Start () {
player = GameObject.Find("Player");
player.transform.position = playerPos;
speed = 100.0f;
hit = new RaycastHit();
//speed = speed * Time.deltaTime;
}
//Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Mouse0)) {
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 1000.0f)) {
previousPosition = transform.position;
targetPosition = hit.point;
lerpMoving = 0;
}
}
}
if(lerpMoving < 1)
movePlayer();
}
void movePlayer(){
lerpMoving += Time.deltaTime;
transform.position = Vector3.MoveTowards(previousPosition, targetPosition, speed * lerpMoving);
}
}
}