How to make a 2D object, which can be moved left and right, constantly fall downwards?
The game I'm working on is in 2D. I'm trying to get the player character, who can fly left & right, to be always gradually floating downwards (regardless of direction on X). I'm not too great at code, so any help would be very much appreciated. I just need help with the floating down part. The player starts off in the air.
Could it be as simple as just setting the gravity on the player to very, very low? (I can't test this until tomorrow)
I prefer Unityscript, but C# will do too.
Thank you.
Answer by NinjaISV · Nov 24, 2015 at 03:43 AM
Just add a Rigidbody2D component to the gameobject then set its "Gravity Scale" to a really low number to make it fall slower. It falls slower because it's being affected less by gravity the lower its "Gravity Scale" is. In addition to falling down, if you want to move the object to the left and right, just add a script with this code to the object.
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float speed = 2f;
Rigidbody2D rigidbody2d;
void Awake () {
rigidbody2d = GetComponent<Rigidbody2D> ();
}
void FixedUpdate () {
if (Input.GetKey (KeyCode.LeftArrow))
rigidbody2d.velocity = new Vector2 (speed * -1, rigidbody2d.velocity.y);
if (Input.GetKey (KeyCode.RightArrow))
rigidbody2d.velocity = new Vector2 (speed, rigidbody2d.velocity.y);
}
}
All this is doing is grabbing the Rigidbody2D
component at the beginning of the game, then just changing its velocity based on what the player's pressing on the keyboard. You can even change how fast it moves left and right by changing the speed
variable in the inspector.
Yup, the gravity thing worked afterall. Thank you for taking the time to answer me.