- Home /
How to make character face direction of target?
I'm trying to make my enemy follow a path but also face the direction of the current target. Below is my code:
public class enemy : MonoBehaviour { public Transform[] target; public float speed; private int current;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (transform.position != target [current].position) {
Vector3 pos = Vector3.MoveTowards(transform.position, target[current].position,speed *Time.deltaTime);
GetComponent<Rigidbody>().MovePosition(pos);
}
else current = (current + 1) % target.Length;
}
}
What can I add in this to make my enemy just face the current target it is going to?
Thanks for the help!
Transform.LookAt Rotates the transform so the forward vector points at /target/'s current position.
Then it rotates the transform to point its up direction vector in the direction hinted at by the worldUp vector. If you leave out the worldUp parameter, the function will use the world y axis. worldUp is only a hint vector. The up vector of the rotation will only match the worldUp vector if the forward direction is perpendicular to worldUp.https://docs.unity3d.com/ScriptReference/Transform.LookAt.html
Answer by leech54 · May 10, 2017 at 01:29 PM
if Y is the axis you want to rotate around you could
float angle = Mathf.Atan2(target.x-charPos.x,target.z-charPos.x) * Mathf.Rad2Deg;
Vector3 newVec = new Vector3(0f,0f,0f);
newVec.y = angle;
transform.eulerAngles = newVec;
Here is another way
Vector3 deltaVec = target.transform.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(deltaVec);
transform.rotation = rotation;
Answer by darchyneer · May 08, 2017 at 01:34 PM
I think you need to add a transform.lookat(). Something like Transform.lookat(the transform of whatever u what it to see). Public Transform target; then add Transform.Lookat(target) in your code.
I've tried the transform.lookat(). $$anonymous$$eeps co$$anonymous$$g up as an error. Can either of you give me an example of how am I suppose to write my line? It just doesn't seem to work. Or when it does, it will only look at the first target. Not the current target.
Answer by poop19999333 · May 08, 2017 at 01:40 PM
I've tried the transform.lookat(). Keeps coming up as an error. Can either of you give me an example of how am I suppose to write my line? It just doesn't seem to work. Or when it does, it will only look at the first target. Not the current target.
Your answer
![](https://koobas.hobune.stream/wayback/20220612121301im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How can I Make a path for Camera ? 1 Answer
Rigidbody trying to follow a spline with smoothing 1 Answer
Character moves along pre-defined path / curve 1 Answer
Make an NPC follow player? 1 Answer
Collider is not working... 2 Answers