I have a problem with when my player needs to fall. The player is falling very slowly. I got that problem is in my script because when I turn off the script, the player is falling in normal acceleration.
Can you help me? I tried to figure out the problem in my code and tried to use ChatGPT for help, but I don't understand. I am new at Unity. Here is my code:
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class Player : MonoBehaviour
{
Rigidbody rb;
public GameObject trigger;
public GameObject camera;
public float speed;
public float rotationSpeed;
public Animator anim;
public float jump;
public bool isGrounded = true;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
---
// Update is called once per frame
void FixedUpdate()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
// Calculate the movement direction based on input
Vector3 cameraForward = Vector3.ProjectOnPlane(camera.transform.forward, Vector3.up).normalized;
Vector3 cameraRight = Vector3.ProjectOnPlane(camera.transform.right, Vector3.up).normalized;
Vector3 moveDirection = cameraForward * verticalInput + cameraRight * horizontalInput;
moveDirection.Normalize();
if (moveDirection != Vector3.zero)
{
// Calculate the target rotation based on the movement direction
Quaternion targetRotation = Quaternion.LookRotation(moveDirection, Vector3.up);
// Smoothly rotate the character towards the target rotation
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
// Move the character
rb.velocity = moveDirection * speed;
if(Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))
{
anim.SetInteger("swr", 1);
}
else
{
anim.SetInteger("swr", 0);
}
}
//private void OnCollisionEnter(Collision collision)
//{
// if (trigger.CompareTag("Cloud"))
// {
// isGrounded = true;
// }
// else
/// {
// isGrounded = false;
// }
//}
}
You do
rb.velocity = moveDirection * speed;
which completely ignores gravity. You copletely overrule the velocity with the new one which is only based on input
You should probably maintain the Y
axis component and do e.g.
var velocity = moveDirection * speed;
velocity.y = rb.velocity.y;
rb.velocity = velocity;
Additionally you also shouldn't use
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
but rather also for that one go through
rb.MoveRotation(Quaternion.RotateTowards(rb.rotation, targetRotation, rotationSpeed * Time.deltaTime));