- Home /
Click to move and facing to move direction?
Hey guys, So im trying to make a top down game where you click to move, everything is working besides the player doesn't face the direction its moving properly. Sometimes it just moves backwards towards the place clicked, i was wondering if anyone can see what ive done wrong here, any help is appreciated.
using UnityEngine;
using System.Collections;
public class movement : MonoBehaviour
{
public Ray ray;
public GameObject player;
public Vector3 newPos;
RaycastHit hit;
Vector3 moveDir;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
ray = Camera.mainCamera.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit))
{
if (Input.GetMouseButton (0))
{
newPos = new Vector3 (hit.point.x, 2.2f, hit.point.z);
player.transform.position = Vector3.Lerp (player.transform.position, newPos, Time.deltaTime);
moveDir = newPos;
moveDir = new Vector3 (newPos.x, 0.0f, newPos.z);
player.transform.rotation = Quaternion.LookRotation(moveDir * rotationSpeed);
}
}
}
}
Answer by robertbu · Sep 18, 2013 at 02:20 PM
Your problem is that LookRotation() takes a vector relative to the characters position, not a world point. I'm assuming you are using the '2.2f' to move the hit point up to the level of the character's pivot. If so, you can fix your code in a couple of different ways. First you could eliminate lines 31 - 33 and replace them with:
player.transform.LookAt(newPos);
Or if you still want to use LookRotation:
player.transform.rotation = Quaternion.LookRotation(newPos - player.transform.position);
hey thanks for the reply, i tried what you suggested it still has the problem, if you hold the mouse button it works fine, but if you click on different spots it doesnt rotate and move to that, it simply moves to that spot,
In your original questions you say, "everything is working besides the player doesn't face the direction its moving properly," so I'm guessing on how you want this to function. Your rotation and movement code is inside the '`if (Input.Get$$anonymous$$ouseButton(0)`', so it is only going to move/rotate if the mouse button is pressed down. As a guess, you might be looking for this functionality:
using UnityEngine;
using System.Collections;
public class $$anonymous$$ovement3 : $$anonymous$$onoBehaviour
{
public GameObject player;
public float speed = 1.0f;
private Vector3 newPos;
void Update ()
{
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit))
{
newPos = new Vector3 (hit.point.x, 2.2f, hit.point.z);
}
}
player.transform.position = Vector3.Lerp (player.transform.position, newPos, Time.deltaTime * speed);
player.transform.LookAt(newPos);
}
}
Thanks for your help!! i thought it was more complicated than that.