- Home /
Jumping effectively in a 2D sidescroller
So, I´m developing a pretty simple 2D sidescroller.
The player basically has two actions: switching through layers in the scenery and jumping obstacles.
Regarding the switching layers component, it´s all set and working. On what it comes to the jumping function, tough, I´m facing some troubles regarding "delay" in the response.
As you can see in my PlayerJump script below, I´m using FixedUpdate() and a Jump() function to take care of the jumping action:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerJump : MonoBehaviour {
private Rigidbody2D player;
private PlayerResponse resp;
public float speed;
public float jumpUntil;
public float impulse;
public Transform playerY;
private float yAxis; // y position when player is not in the air
// Use this for initialization
void Start ()
{
player = GetComponent<Rigidbody2D>();
resp = GetComponent<PlayerResponse>();
playerY = GetComponent<Transform>();
//Gets the coordinate of the player in the Y axis
yAxis = playerY.transform.position.y;
}
// Update is called once per frame
void Update () {
}
void FixedUpdate()
{
Jump();
if (playerY.transform.position.y <= yAxis)
{
playerY.position.Set(playerY.position.x, yAxis, 0);
player.constraints = RigidbodyConstraints2D.FreezePositionY;
}
Jump();
}
void Jump()
{
if(playerY.transform.position.y > yAxis)
{
return;
}
if(resp.pressedOnce())
{
Debug.Log("JUMPED");
player.constraints = RigidbodyConstraints2D.None;
player.AddForce(Vector2.up * impulse);
return;
}
}
}
The "jumping" on itself is working: the player presses the space bar, and jumps. The thing is, a lot of times, when pressing the space bar, the jump doesn´t effectively work for some reason, and is essentially ignored, while other times it isn´t.
I´ve heard this ignorance might be due to using FixedUpdate() and something about it not being as constantly called as Update() is. But I´ve also heard you can´t do physics stuff on Update().
So how should I proceed here? How can I make sure that every time the player presses the space bar, the jump happens without exception?
Your answer
Follow this Question
Related Questions
Jump only when Jump button is pressed - not held 1 Answer
I need help with fixing my "up special" mechanic. 1 Answer
Better 2D Sprite Jump in 3D Plane 1 Answer
Long press for charged Jump 1 Answer
Raycast2D not working 1 Answer