- Home /
AI Lookat script Only using the z axis
How can I make an AI lookat script with only the z axis rotating?
var target;
function Start()
{
target = GameObject.CompareTag("Player"); // this might be wrong cuz I wrote it on my phone
}
function Update()
{
//Look at
}
Answer by DanSuperGP · Feb 26, 2015 at 07:34 PM
Vector3 toTargetVector = target.position - transform.position;
float zRotation = Mathf.Atan2( toTargetVector.y, toTargetVector.x )*Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3 ( 0, 0, zRotation);
This points the X axis at the target... if you want to point the Y axis at the target replace the second line with ...
float zRotation = ( Mathf.Atan2( toTargetVector.y, toTargetVector.x )*Mathf.Rad2Deg ) -90.0f;
$$anonymous$$an, almost 2 year later, I love you! I spent all day looking for a solution, can't find it until now! You're the man!
Answer by siaran · Feb 26, 2015 at 06:05 PM
Maybe something like:
Vector3 target;
void Update(){
transform.LookAt(target);
transform.rotation.eulerAngles = new Vector3(0,0, transform.rotation.eulerAngles.z);
}
I wrote it something like this and it gives me errors. I'm pretty new to C# :P
using UnityEngine;
using System.Collections;
public class AILookat : $$anonymous$$onoBehaviour {
public Transform target;
public Vector3 targetpos;
void Start () {
targetpos = target.transform.position;
}
void Update(){
transform.rotation = transform.LookAt(target);
transform.rotation.eulerAngles = new Vector3(0,0, transform.rotation.eulerAngles.z);
}
}
...what errors?
edit: You should do transform.LookAt(targetpos) or transform.LookAt(target.position) ins$$anonymous$$d of transform.LookAt(target), since you have target as a Transform rather than a Vector3.
got these errors AILookat.cs(16,27): error CS1612: Cannot modify a value type return value of UnityEngine.Transform.rotation'. Consider storing the value in a temporary variable AILookat.cs(15,27): error CS0029: Cannot implicitly convert type void' to `UnityEngine.Quaternion'
Oh, right, you don't need to say transform.rotation = transform.LookAt(target), ins$$anonymous$$d just do
transform.LookAt(target), will edit in my answer.
Your answer
Follow this Question
Related Questions
how to detect if transform.lookat is going through walls? 1 Answer
Zombie AI Help 2 Answers
Look at and animal ai 0 Answers
Make LookAt only rotate X Axis 1 Answer
look at target problem 2 Answers