Quaternion.slerp only on the y axis

Hey I’ve been making an AI script today, ran into alot of problems if you look at the qeustions I made only today… anyway this is another part of the script:

 using UnityEngine;
    using System.Collections;

public class EnemyScript : MonoBehaviour {

	public int health = 100;
	public int rotationSpeed = 1;
	public int moveSpeed = 1;
	
	public GameObject[] gos;
	public GameObject closestPlayer = null;
	public float distance;
	
	void Start(){
		InvokeRepeating("FindClosestPlayer", 0.5f,0.5f);
	}
	
	void FixedUpdate(){
		if(closestPlayer != null){
			transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(closestPlayer.transform.position - transform.position), rotationSpeed * Time.deltaTime);
			transform.position += transform.forward * moveSpeed * Time.deltaTime;
		}
	}

ok the script does what I want, it looks at the player and wals forward at a certain speed, but it looks at the player in all axis, like if I jump he rotates on the x axis, and I don’t want that to happen, I only want the Quaternion.Slerp work on the y axis, this is what I’ve tried to do:

using UnityEngine;
using System.Collections;

public class EnemyScript : MonoBehaviour {

	public int health = 100;
	public int rotationSpeed = 1;
	public int moveSpeed = 1;
	
	public GameObject[] gos;
	public GameObject closestPlayer = null;
	public float distance;
	
	void Start(){
		InvokeRepeating("FindClosestPlayer", 0.5f,0.5f);
	}
	
	void FixedUpdate(){
		if(closestPlayer != null){
			transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(closestPlayer.transform.position - transform.position), rotationSpeed * Time.deltaTime);
			transform.position += transform.forward * moveSpeed * Time.deltaTime;
		}
		transform.rotation = Quaternion.Euler(new Vector3(0f,transform.rotation.y,0f));
	}

I don’t know why but this way it doesn’t rotate at all, like it goes straight forward, and doesn’t rotate to look at the player, help would be apreciated.

Thanks in advance.

1 Answer

1

Hi,
transform.rotation is a quaternion itself. using its y component doesn’t give you what you expect.

try using
transform.rotation = Quaternion.Euler(new Vector3(0f,transform.eulerAngles.y,0f));

cheers

Thanks it worked :D , people are being so nice to me today :)

btw can I make rigidbodies collide but don't interact with each other?