- Home /
How to jump in 2D?
OK, this may be a noob question, but I have this script for my 2D platformer, and I am not sure what is wrong with it. Here is my code (C#):
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public Transform groundCheck;
public float jumpForce;
public bool jump = false;
private bool grounded = false;
void Start () {
}
void Update ()
{
float x = Input.GetAxis ("Horizontal");
transform.Translate (x / 10, 0f, 0f);
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
if (Input.GetButtonDown ("Jump") && grounded)
{
jump = true;
}
}
void FixedUpdate ()
{
if (jump) {
rigidbody2D.AddForce(new Vector2(0f, jumpForce));
jump = false;
}
}
void OnCollisionEnter2D ()
{
if (gameObject.tag == "Floor") {
grounded = true;
} else {
grounded = false;
}
}
}
I also have a sprite called 'Floor' and that has the layer 'Ground'.
When I press SPACE, the sprite does not move at all.
All help is appreciated! I hope I get an answer!
I think you have to view this video Character Controller
Answer by Pyrian · Aug 23, 2014 at 05:00 PM
The AddForce used to jump is overridden and nullified by the Translate command in Update. If you're simply setting the object's location, forces can't come into play.
The two usual solutions are to either double down on forces and do all movement within the physics engine, or to use forces while jumping and then revert to hard sets once you're on the ground again.
Your answer
Follow this Question
Related Questions
2D Platformer Jump while Running Android 1 Answer
Advice needed on my first c# 2D jump script 1 Answer
2D Platformer - Jump on platforms in Background 1 Answer
2D jumping raycast question 0 Answers