- Home /
How can rotate the gameobject only around the y axis?
The gameobject should rotate only around y axis. PlayerDistance should not be changed. i need this for another script. The gameobjects should look to the player. (when the playerdistance < 10) (my english is bad sorry).
using UnityEngine; using System.Collections;
public class NM2 : MonoBehaviour {
public Transform player;
public float playerDistance;
public float rotationDamping;
public float x = 10f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
playerDistance = Vector3.Distance(player.position, transform.position);
if (playerDistance < x)
{
lookAtPlayer();
}
}
void lookAtPlayer()
{
Quaternion rotation = Quaternion.LookRotation(player.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationDamping);
}
Please remember to format your code with the 101010 button.
If the current rotation and desired rotation only involve the Y axis, you can probably get the desired behavior by using Quaternion.Lerp() ins$$anonymous$$d of .Slerp()
If this does not work in your situation, please try to explain further.
Best,
Answer by jshaw3 · Aug 21, 2019 at 07:27 PM
I was using ARFoundation and had a character I always wanted to face the AR Camera. I was having some trouble getting lookAt to work correctly and only rotating on the Y-axis. Using lookat the character seemed to always rotate on all 3 axis.
I found an old Reddit post talking about Mathf.Atan2. I found it really helpful to calculate the angle between two points and rotate the character on the y axis only. Found it very helpful.
https://docs.unity3d.com/ScriptReference/Mathf.Atan2.html
Original Reddit post is here: https://www.reddit.com/r/Unity3D/comments/1m1dzf/c_transformlookat_on_y_axis_only/
Your answer
Follow this Question
Related Questions
Rotate an Instantiated GameObject a set amount from another instantiated GameObject? 1 Answer
How can I rotate around an already rotated axis? 1 Answer
How would I interpret angular displacement from target rotation to max out at 180°? 3 Answers