- Home /
Why does using the velocity of y for the y velocity value work to simulate gravity?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : MonoBehaviour {
public Rigidbody rb;
public float forwardForce = 1000;
public float sidewaysForce = 50;
public float downwardForce = 20;
int movementX;
// Start is called before the first frame update
void Start()
{
movementX = 0;
}
void FixedUpdate()
{
if (transform.position.y > 1.1)
{
rb.AddForce(0, -downwardForce, 0);
}
if (transform.position.y < 0)
{
FindObjectOfType<GameManager>().EndGame();
}
rb.velocity = new Vector2(movementX, rb.velocity.y);
}
// Update is called once per frame
void Update()
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime * 100);
if (Input.GetKeyDown("right") || Input.GetKeyDown("d"))
{
//rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
movementX = 15;
}
if (Input.GetKeyDown("left") || Input.GetKeyDown("a"))
{
//rb.AddForce(-1 * sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
movementX = -15;
}
if (Input.GetKeyUp("right") || Input.GetKeyUp("d"))
{
movementX = 0;
}
if (Input.GetKeyUp("left") || Input.GetKeyUp("a"))
{
movementX = 0;
}
}
}
Basically I have this code here and it works but I'm not exactly sure why. I was hoping someone could explain to me why rb.velocity = new Vector2(movementX, rb.velocity.y); simulates gravity and if I was to replace to "rb.velocity.y" with zero than my object floats.
Answer by Kishotta · Mar 05, 2019 at 08:51 PM
This is kind of an artifact of the Unity API for Vector2 (and 3 and 4). You can't just do myVector.x = 5
to alter a vector because the way the Vector
structs are designed, the .x
, .y
, and .z
properties return a copy of their values. So you'd be setting some value equal to another value, but not actually changing your vector.
The physics system automatically updates the Velocity values of all rigidbodies, so when you create your new Vector with rb.velocity = new Vector2 (movementX, rb.velocity.y);
you are overwriting the velocity by constructing a new Vector that has a new horizontal value, but preserves the old vertical value that was supplied to the rigidbody by the physics system (gravity in your case).
When you don't pass in the old (physics supplied) vertical component to the new movement vector, the gravity isn't preserved and your object appears to float. You're essentially just throwing away the physics system's gravity numbers.