Answer the question
In order to leave comments, you need to log in
How to add code so that a player without support cannot jump?
In unity, a beginner, I work in 2D, I ran into such a problem that if you hold down the space bar, the character will fly up indefinitely. We need the code to check if there is a sprite with the Box Collider 2D component under the character, and then perform a jump, if not, it is idle.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class controller : MonoBehaviour
{
[Header("Player velocity")]
public int xVelocity = 5;
public int yVelocity = 8;
private Rigidbody2D rigidBody;
private void Start()
{
rigidBody = gameObject.GetComponent<Rigidbody2D>();
}
private void Update()
{
updatePlayerPosition();
}
private void updatePlayerPosition()
{
float moveInput = Input.GetAxis("Horizontal");
float jumpInput = Input.GetAxis("Jump");
if (moveInput < 0)
{
rigidBody.velocity = new Vector2(-xVelocity, rigidBody.velocity.y);
}
else if (moveInput > 0)
{
rigidBody.velocity = new Vector2(xVelocity, rigidBody.velocity.y);
}
if (jumpInput > 0)
{
rigidBody.velocity = new Vector2(rigidBody.velocity.x, yVelocity);
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question