- Home /
How do I connect my jump button to my player script?
i'm using the standard assets CrossPlatformInput and I can't figure out how to write the script that allows my player to jump when a button is pressed - I and making an android mobile game so need to be able to touch the buton to make the character jump.. Help please!
Here's my character script..
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.CrossPlatformInput;
public class Move : MonoBehaviour {
private Rigidbody2D rb;
private float dirX, dirY, moveSpeed;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody2D>();
moveSpeed = 5f;
}
// Update is called once per frame
void Update()
{
dirX = CrossPlatformInputManager.GetAxis("Horizontal") * moveSpeed;
dirY = CrossPlatformInputManager.GetAxis("Vertical") * moveSpeed;
}
private void FixedUpdate()
{
rb.velocity = new Vector2(dirX, dirY);
}
void OnTriggerEnter2D(Collider2D triggerCollider)
{
}
}
Answer by xibanya · Dec 27, 2019 at 09:20 PM
looks like you aren't checking if the jump button is ever pressed. at the top of the script have a private const string JUMP = "Jump"
or whatever you've named the jump button. Have a value like public float jumpForce = 10;
that you can set in the inspector, as well as public float gravity = 15;
or something like that.
Then in your update loop,
if (Input.GetButtonDown(JUMP)) dirY += jumpForce * Time.deltaTime;
else dirY -= gravity * Time.deltaTime;