- Home /
Question by
adisali2009 · Sep 29, 2020 at 10:58 AM ·
c#game object
How would I make my player fall properly?
,I wanna make my player fall but instead, he just feathers down and gravity doesn't take effect. I have the use of gravity checked on my rigidbody, and I skimmed through my movement script and it doesn't seem that anything was affecting it
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float Speed;
private Rigidbody rb;
public bool isGrounded = true;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float hmove = Input.GetAxis("Horizontal");
float vmove = Input.GetAxis("Vertical");
Vector3 Direction = new Vector3(hmove, 0, vmove);
Direction.Normalize();
rb.velocity = transform.TransformDirection(Direction * Speed);
if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
{
isGrounded = false;
rb.AddForce(new Vector3(0, 5000, 0), ForceMode.Impulse);
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Ground")
{
isGrounded = true;
}
}
}
Comment
(The 5000 jump force was intentional because of the gravity).
Answer by rh_galaxy · Sep 29, 2020 at 12:25 PM
You have to set the Mass and Drag of the RigidBody in the Inspector. Also I believe that when you do
rb.velocity = transform.TransformDirection(Direction * Speed);
You will overwrite the Y axis velocity so it becomes 0 every frame, Instead you can preserve the velocity.y
Direction.y = rb.velocity.y; //keep current Y
rb.velocity = transform.TransformDirection(Direction * Speed);
Or you could go over to using rb.AddForce() for X and Z as well.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Issue's With Positioning 0 Answers