- Home /
Player slows down when jumping/velocity changes
Fairly new to Unity/C# here.
I'm making a 2D endless runner, with the player having a constant velocity change to the right, and a velocity change for jumping (trying the constant move with forces doesn't work as I don't want acceleration). I've got the player's constant movement somewhat - around 30 or so. What I don't get is why it's not fixed at 30 according to my code. When I jump, the player's movement slows again - from 30 to 25. I can't seem to find out why that happens.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterControl : MonoBehaviour {
public float RightSpeed; // speed for character's movement, it's at 30
public float JumpForce;
Rigidbody2D rb;
bool SpacePressed;
bool isOnGround;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void OnCollisionEnter2D (Collision2D col){
if (col.gameObject.tag == "Ground") {
isOnGround = true;
// Debug.Log ("The player is grounded");
}
}
void Update () {
if (Input.GetKey (KeyCode.Space)) {
SpacePressed = true;
} else {
SpacePressed = false;
}
}
void JumpFunction () {
// Jump Code - using velocity changes
rb.velocity += (Vector2.up * JumpForce);
}
void FixedUpdate () {
Debug.Log (rb.velocity.x);
// Constant move right - using velocity changes
Vector2 directionRight = rb.velocity + Vector2.right;
rb.velocity = directionRight.normalized * RightSpeed;
//Jump execution
if (SpacePressed == true && isOnGround == true) {
JumpFunction ();
isOnGround = false;
}
}
}
Any help would be appreciated, thanks!
Answer by JonPQ · Jan 26, 2018 at 06:49 PM
the problem is you are adding a vertical component to your movement vector, and then normalizing it.
This reduces the vector length back to length of 1.0 (so it shortens both the Y part, and the X part of your vector.
Either... don't normalize it. or... Keep the Horizontal(run) and vertical(jump) vectors as separate variables, and add them to position separately.