- Home /
transform.LookAt on Y axis only? (C#)
Hey people. I'm stuck in my game because i need my mobs to only look at the player on the axis. When the mobs walks over to me they also look up while walking since i'm on a higher spot than them. This also causes them to stand in front of me while looking up and hitting me. So i wanted to add a gravity to them and make them only rotate on the Y axis. Since i can't say transform.LookAt(target.transform.position.y) what would then be the easiest solution?
Thanks in advance.
Answer by Cherno · May 19, 2014 at 02:01 AM
Here's a piece of code from one of my projects, you need to convert it to C# but it works.
var isTurning : Boolean;
var turnSpeed : float = 5.0f;
function TurnTowards(lookAtTarget : Vector3)
{
if(isTurning == false)
{
var aimingDirection = lookAtTarget - transform.position;
var qTo : Quaternion;
var angle = -Mathf.Atan2(aimingDirection.z, aimingDirection.x) * Mathf.Rad2Deg + 90.0;
angle = Mathf.Round(angle / 45.0f) * 45.0f;
qTo = Quaternion.AngleAxis(angle, Vector3.up);
for (var u = 0.0; u <= 1.0; u += Time.deltaTime * turnSpeed)
{
isTurning = true;
transform.rotation = Quaternion.Slerp(transform.rotation, qTo, u);
yield;
}
isTurning = false;
}
return;
}
Answer by bubzy · Sep 09, 2013 at 04:13 PM
using UnityEngine;
using System.Collections;
public class lookyHere : MonoBehaviour {
// Use this for initialization
public Transform target;
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 tempPos = new Vector3(0,target.position.y,0); //this will only affect the y axis, you can shuffle the values around to make it only x or only z or a combination of any.
transform.LookAt(tempPos);
}
Answer by milanfonken · May 18, 2014 at 08:54 PM
Just add a Rigidbody on your object and froze the X-axis and Z-axis That should work
False. Transform.LookAt has nothing to do with physics simulation. Constraining a rigidbody only affects physics simulation done on that gameobject. You can change the transform of any gameobject, it is absolutely not related to the rigidbody.
Your answer
Follow this Question
Related Questions
the textures look bad 1 Answer
Transform.rotation.y rotating around x and z... 1 Answer
Speed issues, cannot change speed, Help 1 Answer
UI element wont destroy 0 Answers