- Home /
AddForce vs Velocity issues with Rigidbody2D
I'm trying to make a basic 2D game, where the character controls a 2D hand sprite and needs to flip a pizza. I'm able to use Rigidbody.AddForce to the pizza (when the player inputs, for now I've set that to the W key), however to make it work I have to have Gravity Scale set to 0, which means the pizza can't fall back down. This prevents you from being able to further play the game.
If I set the Y-axis velocity when the player inputs W, you can force the pizza to go up even though it's no longer in contact with the hand. I can't seem to figure out a solution, as I haven't worked with Unity's physics much.
The code is in UnityScript, by the way.
#pragma strict
var collided = false;
var thrust: float;
var pizza = GameObject.Find("pizza-small").GetComponent.<Rigidbody2D>();
//hand + pizza collision detection
function OnCollisionEnter2D(coll: Collision2D) {
if (coll.gameObject.tag == "Pizza") {
collided = true;
Debug.Log("Hand+Pizza");
}
}
function Update() {
//Input
if (Input.GetKey(KeyCode.W) && collided === true) {
Debug.Log("Up");
transform.position.y+= 0.2;
//Adding force to the pizza
pizza.velocity = Vector3(0,5,0); //or use pizza.AddForce(transform.up * thrust); - AddForce must have gravity scale set to 0, negating gravity. issue with velocity is that you add velocity, you add force even though hand isn't in contact
}
else if (Input.GetKey(KeyCode.A) || Input.GetKey("left")) {
Debug.Log("Left");
transform.position.x-= 0.1;
}
else if (Input.GetKey(KeyCode.D) || Input.GetKey("right")) {
Debug.Log("Right");
transform.position.x+= 0.1;
}
else if (Input.GetKey(KeyCode.S) || Input.GetKey("down")) {
Debug.Log("Down");
transform.position.y-= 0.1;
}
else if (transform.position.y > -3.5) {
transform.position.y-= 0.25;
}
}
Answer by Ali_Jaffer · Jul 23, 2015 at 01:17 PM
Try this. hope this will solve your problem
if (Input.GetKey(KeyCode.W) && collided === true) {
Debug.Log("Up");
transform.position.y+= 0.2;
//Adding force to the pizza
pizza.velocity = Vector3(0,5,0);
collided = false;
}
if(collided == false)
{
debug.Log("down");
pizza.velocity = Vector3(0,0,0);
}
my answer was almost same check the code you was adding velocity when collided = true; but you was not changing the value of collided= false therefore it remain always true
Answer by oscar_wong67 · Jul 24, 2015 at 10:40 AM
I solved it, I just had to make the collided variable stay false unless the proper conditions were met. I got velocity to work, so I'll just use that.