- Home /
Question by
Ez4Noobs · Oct 11, 2021 at 12:33 PM ·
jumping object
I made a code that my 2d character jump, but it keeps going up and idk how to fix this. I need my character to jump once and fall to the ground.
using UnityEngine;
public class playermovement : MonoBehaviour {
Vector2 moveForward;
bool canGoForward = true;
bool canGoOtherDirection;
void Update () {
if (canGoForward) {
moveForward = gameObject.transform.position; //When the game starts it will start to go to the right
moveForward.x += 0.03f;
gameObject.transform.position = moveForward;
}
if (canGoOtherDirection)
{
moveForward.y += 0.01f;
gameObject.transform.position = moveForward;
}
if (Input.GetMouseButtonDown(0)) //When space is pressed, it will start to go up
{
canGoForward = false;
canGoOtherDirection = true;
}
}
}
Comment
Answer by swanne · Oct 11, 2021 at 01:17 PM
Hi,
I like to use the Rigidbody2D component and the isGrounded technique. Here are the relevant snippets of a basic example. This isn't working, complete code; just to give you an idea of the concept:
[SerializeField] private float speed, jumpSpeed;
private Rigidbody2D rb;
private Animator animator;
void Start()
{
rb = GetComponent<Rigidbody2D>();
col = GetComponent<Collider2D>();
animator = GetComponent<Animator>();
}
void Update()
{
Move();
SetAnimationState();
}
private void Move()
{
// Read the movement value
float movementInput = playerActionControls.Land.Move.ReadValue<float>();
// Move the player
Vector3 currentPosition = transform.position;
currentPosition.x += movementInput * speed * Time.deltaTime;
transform.position = currentPosition;
}
private void Jump()
{
if (IsGrounded())
{
rb.AddForce(new Vector2(0, jumpSpeed), ForceMode2D.Impulse);
}
}
private bool IsGrounded()
{
// Basic "Is allowed to jump" logic. This just allows a jump action if the chacter is not already moving up - works for this game though
if (rb.velocity.y > -0.5 && rb.velocity.y < 0.5)
{
return true;
}
else
{
return false;
}
}
Your answer
Follow this Question
Related Questions
swipe player to up jump. 1 Answer
my player continuously jump when i press space-bar 1 Answer
my jump key works about once every 10 presses 1 Answer
jump on collision enter 1 Answer
Why are the player jumps lagging? 1 Answer