Answer the question
In order to leave comments, you need to log in
How to rotate an object relative to local coordinates?
I have a cannon that should rotate horizontally around its own axis. I was somehow able to implement this, but when the vehicle on which it stands drives into an uneven area, it retains its horizontal position, but should repeat the position of the vehicle.
Here is the code:
public class TowerControll : MonoBehaviour
{
public LayerMask maskObstacles;
[SerializeField]
private Transform tower, gun;
[Range(0, 5)]
public float rotSpeed = 1.5f;
[Range(0, 5)]
public float rotSpeedGun = 1.5f;
public int angleDown, angleUp;
private float _rotY, _rotX;
private Vector3 _offset;
private void Start()
{
_rotY = transform.eulerAngles.y;
_rotX = transform.eulerAngles.x;
_offset = tower.position - transform.position;
}
private void LateUpdate()
{
_rotY += Input.GetAxis("Mouse X") * rotSpeed * 3;
_rotX += Input.GetAxis("Mouse Y") * rotSpeedGun * 3;
_rotX = Mathf.Clamp(_rotX, -angleDown, angleUp);
Quaternion rotation = Quaternion.Euler(0f, _rotY, 0f);
Quaternion rotationGun = Quaternion.Euler(-_rotX, _rotY, 0f);
gun.rotation = rotationGun;
tower.rotation = rotation;
transform.position = tower.position - (rotationGun * _offset);
transform.LookAt(tower);
RaycastHit hit;
if (Physics.Raycast(tower.position, transform.position - tower.position, out hit, Vector3.Distance(transform.position, tower.position), maskObstacles))
{
transform.position = hit.point;
transform.LookAt(tower);
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question