- Home /
 
Jumping on moving platforms problem c#
I'm trying to create a code that would let me jump while standing on moving platforms, but I can't think of a way to do it. I wrote a function that checks to see if I'm on a platform and returns true (or false if I'm not), but I want this to be checked whenever I try to jump (with the space bar), such that I can only jump while onPlatform is true.
Basically, how can I program a function that returns booleans to work everytime I press a button? Is that even what I should try to do? Here's my code.
using UnityEngine; using System.Collections;
public class LRmovement : MonoBehaviour { public float speed = 1f; public float JumpSpeed = 10f; private bool onPlatform;
 void Start () {
 }
 void Update () {
     if (Input.GetKey (KeyCode.D) && (transform.position.x < 1.5))
             transform.position += new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
     if (Input.GetKey (KeyCode.A) && (transform.position.x > -1.5))
             transform.position -= new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
 }
 
               }
Answer by KdRWaylander · Jul 20, 2015 at 08:14 AM
Hi,
If IsOnPlateform() is your function that returns a boolean
 bool IsOnPlateform () {
    //something with probably a raycast downward
 }
 
               You just need to call it in an if condition like you do to check if you can move on the right or on the left:
 void Update () {
    //your stuff
 
    if (Input.GetKeyDown(Keycode.Space) && IsOnPlateform())
       Jump();
 }
 private void Jump () {
    //set vertical velocity of your character to 0
    //add a vertical force upward so it jumps
 }
 
              Your answer