How do I get my player to jump while hovering?
Hi,
I'm trying to write a simple script to get my player jump once at a time while hovering. I'm new to unity and just learning how this all works. I've tried to find answers but I couldn't find an answer that I could use in my script.
So I have a hovering boat as a player which controls fine and jumps once when pressing space. After jumping once the jump doesn't work anymore. Any idea how to get the player to jump again and again when it's back from the previous jump? The player needs to hover all the time and not touch the ground.
public class BoatJump : MonoBehaviour { public PlayerControls controller; public float thrustSpeed; public float turnSpeed; public float hoverPower; public float hoverHeight; public float jumpForce = 5f;
private float thrustInput;
private float turnInput;
private Rigidbody shipRigidBody;
private bool OnGround;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<PlayerControls>();
shipRigidBody = GetComponent<Rigidbody>();
OnGround = true;
}
// Update is called once per frame
void Update()
{
thrustInput = Input.GetAxis("Vertical");
turnInput = Input.GetAxis("Horizontal");
}
void FixedUpdate()
{
// Turning the ship
shipRigidBody.AddRelativeTorque(0f, turnInput * turnSpeed, 0f);
// Moving the ship
shipRigidBody.AddRelativeForce(0f, 0f, thrustInput * thrustSpeed);
// Jumping
if (Input.GetButton("Jump") && OnGround == true)
{
shipRigidBody.velocity = new Vector3(0f, jumpForce, 0f);
OnGround = false;
}
// Hovering
Ray ray = new Ray(transform.position, -transform.up);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, hoverHeight))
{
float proportionalHeight = (hoverHeight - hit.distance) / hoverHeight;
Vector3 appliedHoverForce = Vector3.up * proportionalHeight * hoverPower;
shipRigidBody.AddForce(appliedHoverForce, ForceMode.Acceleration);
}
}
}
Answer by Spip5 · Jul 21, 2020 at 05:12 PM
It is pretty hard to tell from your script, but it seems very normal you can't jump anymore since you never put back your OnGround = true (it remains false after the first jump)
Few suggestions :
Put GetButtonDown instead of GetButton.
You can probably check the boat's height to check fi the player can jump again. If height is correct then put OnGround = true
Thank you! Your suggestions helped a lot and I got it working as I wanted.
Your answer
Follow this Question
Related Questions
vibrating jumps and collisions 0 Answers
Touch control swipe up to jump 1 Answer
My game seems to be running too fast for certain tasks 0 Answers
problem with jump script 2 Answers
Help please! Why can't I reduce the speed before jumping? 1 Answer