i created a ball and i want it to roll down a hill it has rigid body and i have a script attached to it for moving and jumping that works but it wont roll down slopes and it has gravity enabled on it what do i do?
We need to see your script in order to help you out here
One thing that comes to mind is you might be setting the velocity instead of changing it, so the physics engine is “trying” to roll the ball down hill, but you’re overriding it every frame.
the script for the movement is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player : MonoBehaviour
{
private CharacterController controller;
private Vector3 playerVelocity;
private bool groundedPlayer;
private float playerSpeed = 9.0f;
private float jumpHeight = 1.0f;
private float gravityValue = -9.81f;
private void Start()
{
controller = gameObject.AddComponent<CharacterController>();
}
void Update()
{
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * playerSpeed);
if (move != Vector3.zero)
{
gameObject.transform.forward = move;
}
// Changes the height position of the player..
if (Input.GetButtonDown("Jump") && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
}
Two separate things going wrong with this code:
1- the CharacterController cannot roll so using one for a ball won’t work. Go look for how to do it with a Rigidbody, which will work with physics, etc.
2- the above code is derivative of defective Unity example code, don’t use it, throw it away now.
For more on part 2 (this is NOT RELEVANT TO YOUR ROLLING BALL!), read this:
I wrote about this before: the Unity example code in the API no longer jumps reliably.
I reported it to Unity via their docs feedback in October 2020. Apparently it is still broken:
https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
Here is a work-around:
https://discussions.unity.com/t/811250/2
I recommend you also go to that same documentation page and ALSO report that the code is broken.
When you report it, you are welcome to link the above workaround. One day the docs might get fixed.
thanks bro i appreciate it but 1 more question if that’s ok. with your script for the movement how do i disable the forwards and backwards movement because if i want a game that is 2d it will fall of somehow if i press “w” or “s” or just a 3d game that i don’t want the player moving forwards and backwards or is there just a better script for that, thanks.