Rotating Movement with Acceleration problem
Hello Everyone. I am developing a space shooter, I am struggling to get the movement right. So far I have managed to get the ship to move, rotate and accelerate to a max value. However the issue is that the way I'm moving currently one the ship reaches max speed it is not able to change its velocity when the angle is between 180 degrees of the direction of travel since that would fail the current check that doesn't allow more than the maximum speed based on the magnitude of the velocity vector. The idea is that while it shouldn't increase the magnitude of the vector accelerating into an angle within 180 degrees of the direction of travel should allow to change the direction of the vector. Here is the code:
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D body;
private float horizontal;
private float vertical;
private Vector3 speed;
public float movementSpeed = 0.1f;
public float rotationSpeed = 4f;
public float maxSpeed = 10f;
public float minSpeed = -3f;
public bool accToggle = true;
public bool invControl = false;
private void Start()
{
body = GetComponent<Rigidbody2D>();
}
private void Update()
{
GetPlayerInput();
}
private void FixedUpdate()
{
MovePlayer();
RotatePlayer();
}
private void GetPlayerInput()
{
// Gives a value between -1 and 1
horizontal = Input.GetAxisRaw("Horizontal"); // -1 is left +1 is right
vertical = Input.GetAxisRaw("Vertical"); // -1 is down
}
private void MovePlayer()
{
if (accToggle)
{
if ((transform.up * Mathf.Clamp(vertical, -0.5f, 1) * movementSpeed + speed).magnitude < maxSpeed)
{
speed += transform.up * Mathf.Clamp(vertical, -0.5f, 1) * movementSpeed;
}
body.velocity = speed;
}
else
{
body.velocity = transform.up * Mathf.Clamp(vertical, -0.5f, 1) * movementSpeed;
}
}
private void RotatePlayer()
{
float rotation;
if (invControl)
{
rotation = horizontal * rotationSpeed;
}
else
{
rotation = -horizontal * rotationSpeed;
}
transform.Rotate(Vector3.forward * rotation);
}
}
Many thanks in advance!
Answer by IntergalacticSlap · Nov 13, 2020 at 08:41 PM
Here is the relevant function cleaned up a bit:
private void MovePlayer()
{
Vector3 target = transform.up * Mathf.Clamp(vertical, -0.5f, 1) * movementSpeed + speed;
if (accToggle)
{
if (target.magnitude < maxSpeed)
{
speed = target;
}
body.velocity = speed;
}
else
{
body.velocity = transform.up * Mathf.Clamp(vertical, -0.5f, 1) * movementSpeed;
}
}
Your answer
Follow this Question
Related Questions
I have no Idea why my highscore Script isn't working ... 0 Answers
Script in Unity responding incorrect values 0 Answers
C# Unity dot syntax exercise correct solution? 1 Answer
Can Someone Explain Why Message does not show Anything In Inspector 0 Answers
Adding prefab object on collision to a another script 0 Answers