Question by
VeryPoorProvider · Mar 16 at 04:41 PM ·
c#bugunity5unity 5.2transform.lookat
Very strange tank turret behavior in Unity 3D
I have a tank with a separate code for the turret:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TowerScript : MonoBehaviour
{
public GameObject player;
void Start()
{
player = GameObject.Find("Tractor");
}
void Update()
{
transform.LookAt(player.transform.position);
}
}
This code should rotate the tower after the player. And it basically works. But for some reason, the tower additionally turns up:
My turrets x is should be always -90. But transform.LookAt always change it to 0. I tried a lot of different variants, but they didn't work. How to fix it?
screenshot-140.png
(127.2 kB)
Comment
This is because Unity considers local-space z+
as "forward" direction.
using UnityEngine;
public class TowerScript : MonoBehaviour
{
[SerializeField] Transform _player;
[SerializeField] Vector3 _auxRotation = new Vector3( -90 , 0 , 0 );
void Update ()
{
transform.LookAt( _player.position );
transform.rotation *= Quaternion.Euler(_auxRotation);
}
}
Your answer
Follow this Question
Related Questions
Unity 5.2 messing up car 0 Answers
Android - Code working in Unity Remote but not in Build 2 Answers
How to limit rotation speed when using Transform.LookAt? 0 Answers
Attribute being assigned on server but not client - Mirror. 0 Answers
Script function being applied to everything it's attached to logic error 2 Answers