Clicking on an object to make player face it
Okay so I have my player object in the centre of the screen, above him is a square, if i click this square I want my player to rotate 180 degrees (because he is facing down) and look at that object. I'm having trouble with coding, I'm trying different code but it isn't working.
Can anyone please give me some help, I'm very new to coding.
Thanks.
Answer by samathon · Mar 07, 2016 at 12:20 AM
Here's the first thing that came to mind for me:
Create a script on the player object with a public function called something like FaceObject() that, when called, uses LookAt() or RotateTowards() to turn it to face the square. LookAt() will be a little easier, but I believe it will just make the player instantly face the object, whereas you can use RotateTowards() to turn it gradually. You can pass in the square (or whatever object to turn to face) as a parameter to FaceObject.
Then create a script on the square with an OnMouseDown() function that calls FaceObject()
Okay so I'm using this script provided by Unity:
using UnityEngine;
using System.Collections;
public class ExampleClass : $$anonymous$$onoBehaviour {
public Transform target;
public float speed;
void Update() {
Vector3 targetDir = target.position - transform.position;
float step = speed * Time.deltaTime;
Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0F);
Debug.DrawRay(transform.position, newDir, Color.red);
transform.rotation = Quaternion.LookRotation(newDir);
}
}
I get how this works but need help with adding in "when the cube is clicked, execute the rotate towards part"
Thanks for the help so far though man.
Your answer
![](https://koobas.hobune.stream/wayback/20220612070636im_/https://answers.unity.com/themes/thub/images/avi.jpg)