- Home /
AddForce based on Angle/Rotation (2D)
I have a small game (2D) where the player chooses an angle and power to try and 'jump' a block in front of them.
My problem is that I have been experimenting with various types of AddForce and inputting different vectors to achieve different results. All do function, but none of them function as planned.
My 'FinalAngle' is achieved by this:
finalAngle = playerCharacter.transform.localEulerAngles;
Which outputs something in the range of (0,0,0) and (0,0,60) depending on where the player stopped the character rotation and my power is an int between 1 and 100.
Almost all attempts lead to either the cube flying massively off screen, or barely moving.
I'd prefer if someone could just guide me through how I can apply these two variables together to get a nice arcing force. Here is the closest I have gotten on my own:
playerBody.AddForceAtPosition(new Vector2 (finalAngle.z, finalAngle.z), new Vector2 (playerCharacter.transform.position.x, playerCharacter.transform.position.y), ForceMode2D.Impulse);
However it doesn't take into account the power, flies the cube off screen and never arcs back down. But at least it seems to get the right angle! xD
Any help very much appreciated, especially if you can point me in the direction of how I can 'predict' (Preferably through some sort of GUI element) how an AddForce will work.
Answer by Pseu · Jul 07, 2015 at 01:12 AM
For those interested I actually managed to create what I needed by changing the velocity of the object directly instead of using AddForce and then fiddling with values a little. The end code ended up looking like this:
void JumpFunction(){
if (!jumpActive){
Rigidbody2D playerBody = playerCharacter.GetComponent<Rigidbody2D>();
playerBody.isKinematic = false;
playerBody.angularVelocity = power*10;
playerBody.velocity = new Vector2 (finalAngle.z*powerAfterConvert, finalAngle.z*powerAfterConvert);
jumpActive = true;
}
if (jumpActive){
Rigidbody2D playerBody = playerCharacter.GetComponent<Rigidbody2D>();
if (playerBody.velocity.x < 0.1){
if (playerBody.velocity.y < 0.1){
currentState = GameStates.RESET;
}
}
}
}
Power is now a float and after the player gets a power (Only int 0-100 possible), I then divide it by 100 so it doesn't fly off the screen.
It isn't a fantastic solution and needs tweaking, but it is certainly a LOT better than where I was it.
I tried your solution, the object wouldn't move at all :/ Care to help me please?