AddRelativeForce() causes unwanted turning

Viewed 256

I've create a movement script that moves a character (ship) in a topdown view. Gravity is disabled, but the rest of the settings i left mostly alone.

I'm applying a constant force in the forward or backward direction (local, so relative to the character NOT the world). This however causes some movement in other directions if the character is rotated for some reason.

                Debug.Log(nameof(force) + force);

                rigidBody2D.AddRelativeForce(force);

Lets me explain with pictures.

Starting point: enter image description here

Moving forward somewhat (works okay): enter image description here

Back to starting point (stopping game, starting anew) And then i manually change the rotation to -90 in the inspector. I then move forward somewhat.

enter image description here

As we can see since the rotation is -90, moving forward in relative to the character (AddRelativeForce(..)) causes it to move to the right on the screen. The X position increments accordingly.

However, also the Y component changes, the character gets velocity in this direction, even though i apply no force in that direction - which we can see in the output.

How can I move my character with force without this issue?

Edit:

Here are the project files. Runs under the latest unity 2020.1.14f1. The logic mentioned here is located in MoveExecuteSystem. I use a small ECS framework: https://github.com/Leopotam/ecs

https://wetransfer.com/downloads/b86dfb27b4388b85ac4fef285d87b39520201124193329/00af66

1 Answers

Take into account that AddRealtiveForce adds the force in the local coords system. If the force vector has got always the same value, the outcome is going to be different depending on the rotational position of the entity. To solve this, you need to apply the force such as: Vector3 force = myShip.forward * forceValue where force value can be an int or a float. It can be myShip.up or myShip.right depending on what you want. My point is that with the .forward, .up or .right you always will apply the force according to the instant local coordinate system rotational position.

EDIT: This question seems deeper than I thought, I made the trial in a project myself, and actually there are variations in the position when you apply force only when the object is rotated. Had a quick look and don't know why this is. Seem to be a precisión thinh regarding the rotations of the physics the rigidbody uses under the hood. I tried to remove the friction which I thought might be also cause of the problem but seems not possible. +1 to this question and lookig forward to know the answer.

EDIT2: Bounciness and friction can be set to 0 if a new physics material 2d is created, but the issue persists. You can freeze position in determined axis as a solution, but this does not explain the position variation problem.

Related