Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice

Question Raycast not working in unity3d

Discussion in 'Physics' started by adityaboi, Feb 3, 2021.

  1. adityaboi

    adityaboi

    Joined:
    Feb 3, 2021
    Posts:
    4
    I implemented a Raycast to check whether the player is on the Ground so that I can jump on while i am on the ground. But it doesnt seem to work. I dont even get the message in Console! Please help. I am beginner who barely knows about raycast.

    Here's the code:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Movement : MonoBehaviour
    {
    public CharacterController Controller;
    [SerializeField] public float speed;
    [SerializeField] public float gravity;
    [SerializeField] public Transform GroundCheck;
    [SerializeField] public float GroundDistance;
    [SerializeField] public LayerMask GroundMask;
    [SerializeField] public float jumpheigt;
    [SerializeField] public float DistanceToGround;
    bool isGrounded;
    bool RaycastCheck;
    Vector3 velocity;

    void Update()
    {
    //Raycast
    RaycastCheck = Physics.Raycast(transform.position, Vector3.down, DistanceToGround);
    if (RaycastCheck)
    {
    Debug.Log("Raycast working");
    }



    //Movement
    float HorizontalMovement = Input.GetAxis("Horizontal");
    float VerticalMovement = Input.GetAxis("Vertical");
    Vector3 Movement = transform.right * HorizontalMovement + transform.forward * VerticalMovement;
    Controller.Move(Movement * speed * Time.deltaTime);

    //Jump

    if (Input.GetButtonDown("Jump") && RaycastCheck == true)
    {
    velocity.y = Mathf.Sqrt(jumpheigt * -2 * gravity);
    }


    //Gravity
    velocity.y += gravity * Time.deltaTime;
    Controller.Move(velocity * Time.deltaTime);
    }

    }
     
  2. AlTheSlacker

    AlTheSlacker

    Joined:
    Jun 12, 2017
    Posts:
    326
    Please use code tags when posting code, it's the little icon with the "<>" symbols on a page icon.

    I don't see anything wrong with your //Raycast section. Are you sure you have set an appropriate value for DistanceToGround? You will want it to be slightly more than the distance from the centre of your character controller to ground. So if your Character Controller has a Height = 2, then try DistanceToGround = 1.05 (i.e. the base of the controller is within 5 cm of the ground).
     
  3. adityaboi

    adityaboi

    Joined:
    Feb 3, 2021
    Posts:
    4
    THANKS!! I set my DistanceToGround Variable to the right amount and it works. I set it so that I can achieve Double-Jump and not more than that. Again, I am so thankful for your help.
     
    AlTheSlacker likes this.