- Home /
Question by
mikolajo2001 · Aug 12, 2021 at 03:51 PM ·
tankrotatetowardsgun movement
How do i limit rotation that uses RotateTowards without making my object vibrate?
I'm trying to make a tank game, where the turret and gun of the tank rotate to a raycast from the main camera. Everything works fine except for the gun elevation, which i want to be limited, so the gun can only rotate a certain amount of degrees up and down. With my code the gun starts to vibrate when it gets to the rotation limit. I've spent way too much time on this already, so any help would be greatly appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunElevation : MonoBehaviour
{
public bool local;
void FixedUpdate()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (local == true)
{
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray, out hit))
{
float rot = transform.localEulerAngles.x;
if(rot>180)
{
rot = rot - 360;
}
Vector3 direction = hit.point - transform.position;
direction = Vector3.ProjectOnPlane(direction, transform.parent.right);
Quaternion target = Quaternion.LookRotation(direction, transform.parent.right);
transform.rotation = Quaternion.RotateTowards(transform.rotation, target, 35 * Time.deltaTime);
if (rot > 10)
{
transform.localEulerAngles = new Vector3(10, transform.localEulerAngles.y, transform.localEulerAngles.z);
}
if (rot < -15)
{
transform.localEulerAngles = new Vector3(-15, transform.localEulerAngles.y, transform.localEulerAngles.z);
}
}
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613041549im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
firing my bullitprefab up and to the side 0 Answers
Changing Meshes - MissingReferenceException 0 Answers
Tank Controller/Script? 1 Answer
Can't Ignore a Layer when raycat 0 Answers
Why when I use Time.deltaTime, it slows down my rotation 1 Answer