Moving and jumping
Hi! I create a moving script and "jumping". But when I holding up arrow character fly no simple once jump. My script:
using UnityEngine;
using System.Collections;
public class Moving : MonoBehaviour {
public float speed = 10f;
public Vector2 maxVelocity = new Vector2(3, 5);
public float JumpPower = 0.25f;
private Rigidbody2D RB;
void Start () {
RB = GetComponent();
}
void Update () {
var forceX = 0f;
var forceY = 0f;
var absVelX = Mathf.Abs(GetComponent().velocity.x);
if (Input.GetKey("right"))
{
if (absVelX < maxVelocity.x)
forceX = speed;
transform.localScale = new Vector3(1, 1, 1);
}
else if (Input.GetKey("left"))
{
if (absVelX < maxVelocity.x)
forceX = -speed;
transform.localScale = new Vector3(-1, 1, 1);
}
GetComponent().AddForce(new Vector2(forceX, forceY));
{
if (Input.GetKey("up"))
{
RB.AddForce(new Vector2(0, JumpPower), ForceMode2D.Impulse);
}
}
}
}
Answer by JScotty · Nov 04, 2016 at 02:36 PM
Your character is flying because it continually adds force when pressing up arrow.
So what you can do is check if it touches the ground, it is able to add force like:
private bool ground = true;
void OnTriggerEnter(){ // enters a collider
ground = true;
}
void OnTriggerExit(){ //exit a collider
ground = false;
}
and then edit your
if (Input.GetKey("up")) {
RB.AddForce(new Vector2(0, JumpPower), ForceMode2D.Impulse);
}
// to
if (Input.GetKey("up")) {
if(ground) {
RB.AddForce(new Vector2(0, JumpPower), ForceMode2D.Impulse);
}
}
Your answer
Follow this Question
Related Questions
Need help with jumping on third person movement script. 0 Answers
Help with jumping script 2 Answers
how to jump in a 2D game 2 Answers
How i make a ball jump where i point with my mouse?[3D] 0 Answers