- Home /
How to remove player control while in the air?
I'm working on a ball racing game, and the player is controlled based on force vectors that move the ball in the direction that the player is pushing on either the joystick or arrow keys. Normally, this works fine, but when the ball is knocked into the air, the player can still move the ball from side to side, which isn't what I want. How do I adjust the script below so that the player cannot move from left to right while in the air?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallControl : MonoBehaviour
{
private Rigidbody rb;
public float accelX = 1.0f;
public float accelY = 1.0f;
public float maxSpeed = 50.0f;
public Transform playerCam;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
//Get player inputs
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
//Change inputs from world xyz to camera xyz
Vector3 camF = playerCam.forward;
Vector3 camR = playerCam.right;
camF.y = 0.0f;
camR.y = 0.0f;
camF = camF.normalized;
camR = camR.normalized;
//Add force to the ball based on camera position
Vector3 movement = ((camF * vertical * accelX) + (camR * horizontal * accelY));
rb.AddForce(movement);
//Speed limit
if (rb.velocity.magnitude > maxSpeed)
{
rb.velocity = rb.velocity.normalized * maxSpeed;
}
}
}
Answer by matthewroxby · Feb 05, 2021 at 09:49 PM
Just create a bool to see if the ball is touching the ground. Put your movement inputs into an if statement like so:
if(grounded == false){
float horizontal = Input.GetAxisRaw("Horizontal")
float vertical = Input.GetAxisRaw("Vertical")
}
As for the grounded code, let me know if you don't know how to do that and I can give you some help :)
Thank you so much! I'm actually a bit new to the C# program$$anonymous$$g language, so I do not know how to create grounded code. If you could give me some instructions that would be awesome!
So the idea for grounded code is to add a small hitbox underneath your character, and add a grounded script to it. Inside the script, do this:
void OnTriggerEnter(Collider other){
//make sure that the collider is a trigger, and set any ground colliders to the ground tag
if(other.tag == "ground"){
//get a reference to your player script and set the grounded variable
player.grounded = true;
}
}
Your answer
Follow this Question
Related Questions
Space shooter player rotation issue 1 Answer
Problem with player bouncing or jumping 1 Answer
Camera based movement 3rd person game,Movement like in 3rd person games (camera based) 1 Answer
Movement with angle in 3d 2 Answers
How can I smooth out and unlock the movement with the input system? 0 Answers