In my game you are a rocket and you try to orbit a planet. So when you press A or D you should rotate left or right. But when you let go of the key you snap back to your original rotation. I don’t know how to fix this or what is wrong.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class RocketController : MonoBehaviour
{
private Rigidbody2D rb;
public float Thrust = 20;
public float rotation = 5;
public float rotationSpeed = 2;
private float speed = 15;
public float weight = 10;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
speed = Thrust / weight ;
rb.AddForce(transform.up * speed );
rb.MoveRotation(rotation);
if (Input.GetKey(KeyCode.A))
{
rb.MoveRotation(rb.rotation - rotationSpeed * Time.fixedDeltaTime);
}
if (Input.GetKey(KeyCode.D))
{
rb.MoveRotation(rb.rotation + rotationSpeed * Time.fixedDeltaTime);
}
}
public void AdjustThrust(float newThrust)
{
Thrust = newThrust;
}
public void AdjustRotate(float newRotate)
{
rotation = newRotate;
}
}
So in your update function, rb.MoveRotation(rotation); is always setting rotation back to the original value of 5 (as the rotation float is never being updated.
You could add AdustRotate(); to your input.getkey functions to update the rotation value, note that you will need to add the newly calculated rotation inside the brackets also.
MovePosition and MoveRotation do not get actioned there and then, it only happens when the physics runs. Physics runs (by default) during the FixedUpdate so calling them per-frame is pointless. If you have 10 frames between each physics update, only the last call you made will be actioned so this is wasteful and can also lead to errors or false assumptions.
MovePosition(PositionA)
MovePosition(PositionB)
Same as above, multiple calls don’t all get actioned, only the last one before the simulation runs does so below, it’ll move to PositionB if nothing else is called before the simulation runs.