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;
}
}