Reputation: 1
image of the scene. I was using a tutorial online, then ran into issues when the code didn't work properly.
My main issue is with the isGrounded variable. When used, it doesnt allow my sprite to jump, when its job is to prevent doube-jumps by only allowing you to jump when touching the ground, everything is linked up to the in-engine components, and i think the main issue is with the line:
isGrounded=Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
the rest of the code is below. thanks for reading.
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 10f;
Vector3 velocity;
public float gravity = -20f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public float jumpHeight = 3f;
public float speedManager = 1.5f;
bool isGrounded;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if( isGrounded && velocity.y < 0)
{
velocity.y = -10f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * (x / speedManager) + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -10f * gravity);
}
controller.Move(velocity * Time.deltaTime);
}
}
Upvotes: 0
Views: 370
Reputation: 992
Check if public LayerMask groundMask;
is set in the component and your ground GameObject's layer is the same as groundMask
.
Edit:
You can add this piece of code to your class to check if the ground check is performed in the correct position:
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawSphere(groundCheck.position, groundDistance);
}
Upvotes: 1