Help.. Jump by Addforce , could you help me? I want my player jump by addforce
This is my "PlayerMovement" ..
public class PlayerMovement : MonoBehaviour {
public float _gravity = 1.5f;
public float _yVelocity = 0.0f;
public float _moveSpeed = 25.0f;
public float _jumpSpeed = 40.0f;
public CharacterController _controller;
private bool _onGround;
Animator anim;
// Use this for initialization
void Start ()
{
_controller = GetComponent<CharacterController>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void FixedUpdate ()
{
_onGround = _controller.isGrounded ; //Gets if the controller is grounded
Vector3 direction = new Vector3(SimpleInput.GetAxis("Horizontal"), _yVelocity, SimpleInput.GetAxis("Vertical")); //Gets the direction
if (direction.sqrMagnitude > 1f) direction = direction.normalized; //This prevents going faster when running diagonically
Vector3 velocity = direction * _moveSpeed; //Multiplies the movement speed
}
else
_controller.Move(velocity * Time.deltaTime);
Vector3 facingrotation = Vector3.Normalize(new Vector3(SimpleInput.GetAxis("Horizontal"), 0f, SimpleInput.GetAxis("Vertical")));
if (facingrotation != Vector3.zero) //This condition prevents from spamming "Look rotation viewing vector is zero" when not moving.
transform.forward = facingrotation;
if (_onGround ) { //JUMPING if (CrossPlatformInputManager.GetButtonDown("Jump")) { // Jump by AddForce script here
}
}
Comment
Answer by $$anonymous$$ · Jan 21, 2021 at 02:45 AM
You need a Rigidbody to use AddForce:
public Rigidbody rb;
void Start(){
if(!rb){
rb = GetComponent(); }
}
void FixedUpdate(){
if (_onGround ) {
//JUMPING
if (CrossPlatformInputManager.GetButtonDown("Jump")) {
// Jump by AddForce script here
Vector3 jumpDirection = Vector3.up * _jumpSpeed;
rb.AddForce(jumpDirection, ForceMode.Impulse);
}
}
}