I have ship that moves forward in the direction the transform is facing. When I rotate this ship, however, I get unexpected movement.
Here’s a gif showing the behavior that I am seeing: https://media.giphy.com/media/1g2C1sk8eHEko24QIq/giphy.gif
What I am expecting is the ship to move the way that the camera is: in a complete circle. But, for some reason, it moves in one direction, then kind of halts, then keeps moving in that one direction.
Here’s the code I am using:
public class TestMovement : MonoBehaviour
{
[SerializeField] Transform childObject;
[SerializeField] float rotationAmount = 40f;
[SerializeField] float smoothing = 2.0f;
[SerializeField] float movementSpeed = 20f;
private void Update()
{
// Get Player Input
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical") * -1;
// Calculate Movement
CalculateMovement(horizontal, vertical);
// Calculate Rotation
CalculateRotation(horizontal, vertical);
// Move forward in direction of transform's forward
transform.position += transform.forward * Time.deltaTime * movementSpeed;
}
void CalculateMovement(float horizontal, float vertical)
{
// Set a Vector 3 with the direction we wish to move in
Vector3 direction = new Vector3(horizontal, vertical, 0);
// Move the ship in the desired direction
transform.position += direction * movementSpeed * Time.deltaTime;
// Rotate the transform for free-range movement
transform.Rotate(0f, horizontal * 1.5f, 0f);
}
private void CalculateRotation(float horizontal, float vertical)
{
Quaternion target = Quaternion.Euler(vertical * -rotationAmount, horizontal * rotationAmount, horizontal * -50f);
childObject.localRotation = Quaternion.Slerp(childObject.localRotation, target, Time.deltaTime * smoothing);
}
}
If you can help me figure out what I’m doing wrong here, I would greatly appreciate it. And just in case it is needed, here’s an image showing the inspector.