How to set a limit on how high a player can jump?
I am a beginner making a 3d platforming game where you have to grab coins and jump onto platforms to grab the coins out of reach from the ground. So I put together code which allows the player to jump. I tried setting a limit to how high they can jump but this prevents them from jumping while on the platforms which are higher that the jump limit. If I try to increase the height limit, this allows the player to jump higher, which I do not want. Here's my code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour
{
private int points;
private Rigidbody rb;
public float speed;
public Text scoredis;
public Text winner;
void Start()
{
rb = GetComponent<Rigidbody>();
points = 0;
PointDisplay();
winner.text = "";
}
void FixedUpdate()
{
if(gameObject.transform.position.y <= 8)
{
float movejump = Input.GetAxis("Jump");
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, movejump, moveVertical);
rb.AddForce(movement * speed);
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pickup"))
{
other.gameObject.SetActive(false);
++points;
PointDisplay();
}
}
void PointDisplay()
{
scoredis.text = "Score: " + points.ToString();
if (points >= 12)
{
winner.text = "You Win!";
}
}
}
Answer by jgodfrey · Jun 30, 2016 at 04:25 AM
As you've realized, the jump "height" shouldn't have anything to do with the current "Y" position of the player,so you don't want this:
if(gameObject.transform.position.y <= 8)
Instead, you probably want to control the value going into the AddForce() call to control the overall height of the jump. You might be able to get away with Mathf.Clamp'ing the Y value used in the force vector to a "sensible" range. Just figure out what force provides the maximum jump you want and then clamp the Y value of your vector to that max...
Unfortunately, this does not solve my problem. What I think is that trying your clamp solution limits how high or low the movejump variable's value is. Even with the clamp, if the player holds down space, it will still add a force upward, but at a slower rate because of the clamp.
I have no idea what your expected game mechanics are, but typically, you'd only allow a jump when the player is grounded and disallow it when they are already mid-jump (with the typical exception being a double-jump). So, the solution I presented should indeed limit the force applied to any single jump, though if you allow that force to be applied each time the space bar is pressed, you're not likely going to get the desired result..
Your answer