Question by
Solar_0 · Nov 09, 2020 at 10:05 PM ·
scripting problemgravityscripting beginner
Unity3d gravity not working in movement script
Hey, I have the following code for character movement which I took from a comment on this question. When applied to my game however, the gravity doesn't seem to be working. I tried fixing it but with my limited coding skills, I can't figure out what the issue is. The original poster of the code doesn't seem to be active anymore, which is why I'm asking here.
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour
{
public float _gravity = 1.5f;
public float _yVelocity = 0.0f;
public float _moveSpeed = 25.0f;
public float _jumpSpeed = 40.0f;
public CharacterController _controller;
void Start ()
{
_controller = GetComponent<CharacterController>();
}
void Update ()
{
Vector3 direction = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); //Gets the direction
if (direction.sqrMagnitude > 1f) direction = direction.normalized; //This prevents going faster when running diagonally
Vector3 velocity = direction * _moveSpeed; //Multiplies the movement speed
_controller.Move(velocity * Time.deltaTime);
if (_controller.isGrounded)
{
if (Input.GetKeyDown(KeyCode.Space))
{
_yVelocity = _jumpSpeed; //Gets the jump height on the Y Axis
}
}
else
{
_yVelocity -= _gravity;
}
Vector3 facingrotation = Vector3.Normalize(new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")));
if (facingrotation != Vector3.zero) //This condition prevents from spamming "Look rotation viewing vector is zero" when not moving.
transform.forward = facingrotation;
}
}
Comment