Hello,
I wrote the following script where the keys a, d, and w move a rigidbody2d using transform.Tanslate(). Meanwhile the arrow keys move the rigidbody2d using rigidbody2d.AddForce(). As I use the keys to move the game object left or right everything works as expected.
But if I press the up arrow or w key the object moves up and then falls back down. Then as the object hits the ground it bounces back up to the same height and repeats like a ball. I just don’t understand why this is happening. Shouldn’t rigidbody2d.AddForce() keep adding an upward force every time the physics updates? Thus if my upward force is larger than the gravitational force then the object should keep moving up. Same for transform.Translate(). Each update I’m trying to move the object up through the Translate() method so each update the object should move up not fall back down.
The rigidbody2d component has 0 linear and rotational drag, gravity of 1, and mass of 1. No special material added or anything. Here is the script I added to the gameobject.
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
public int speed = 5;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
if(Input.GetKey(KeyCode.RightArrow)){
rigidbody2D.AddForce(new Vector2(speed, 0));
}
if(Input.GetKey(KeyCode.LeftArrow)){
rigidbody2D.AddForce(new Vector2(-speed, 0));
}
if(Input.GetKey(KeyCode.UpArrow)){
this.transform.Translate(new Vector2(0, speed*(float)0.04));
}
if(Input.GetKey(KeyCode.D)){
this.transform.Translate(Vector2.right * speed * Time.deltaTime);
}
if(Input.GetKey(KeyCode.A)){
this.transform.Translate(Vector2.right * -speed * Time.deltaTime);
}
if(Input.GetKey(KeyCode.Space)){
this.transform.Translate(Vector2.up * speed * 2 * Time.deltaTime);
}
}
}