Rigidbody2D is falling slowly when using velocity
I am making a super mario style game. I have attached a rigidbody2d to my player and a script to make him run. When you run while falling, the gravity slows down. It works exactly how I want it to until this happens. The scene is at a reasonable scale (1, 1, 1) and the gravity works fine.
Here's the script-
//MarioMove.cs
using UnityEngine;
using System.Collections;
public class MarioMove : MonoBehaviour {
public Animator marioAnimator;
public bool canJump;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void LateUpdate () {
if(Input.GetKey(KeyCode.RightArrow)) {
transform.eulerAngles = new Vector3(0, 0, 0);
GetComponent<Rigidbody2D>().velocity = new Vector2(5, 0);
}
if(Input.GetKeyDown(KeyCode.RightArrow)) {
marioAnimator.SetBool("Run", true);
}
if(Input.GetKeyUp(KeyCode.RightArrow)) {
GetComponent<Rigidbody2D>().velocity = Vector3.zero;
marioAnimator.SetBool("Run", false);
}
if(Input.GetKey(KeyCode.LeftArrow)) {
GetComponent<Rigidbody2D>().velocity = new Vector2(-5, 0);
transform.eulerAngles = new Vector3(0, 180, 0);
}
if(Input.GetKeyDown(KeyCode.LeftArrow)) {
marioAnimator.SetBool("Run", true);
}
if(Input.GetKeyUp(KeyCode.LeftArrow)) {
GetComponent<Rigidbody2D>().velocity = Vector3.zero;
marioAnimator.SetBool("Run", false);
}
}
void Update () {
if(Input.GetKeyDown(KeyCode.UpArrow)) {
if (canJump == true) {
GetComponent<Rigidbody2D>().AddForce (transform.up * 300);
canJump = false;
}
}
}
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Ground") {
canJump = true;
}
}
}
I know this is fairly old but, if you're going to use a component frequently, store it as a class field.. Repeated calls to GetComponent can become quite expensive when scaling up :)
Answer by PointyPigheadGames · Nov 14, 2016 at 12:12 AM
Figured it out myself! Used this code-
//MarioMove.cs
GetComponent<Rigidbody2D> ().velocity = new Vector2 (-5, GetComponent<Rigidbody2D>().velocity.y);
Hope this helps somebody!
Your answer
Follow this Question
Related Questions
Character suddenly stop moving. 0 Answers
Strange behavior when applying forces. 0 Answers
Best solution for 100% accurate jumps. 0 Answers
Colour changing texture. 0 Answers
how to find velocity magnitude relative to transform.right. 2D 2 Answers