- Home /
Raycasting up for crouch
I made a crouch script (I put it in my moving script) and now i wish to make a raycast up, to know if the player is going to hit the roof. The crouching script just sizes down the player. Whatever, here's my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ControllingScript : MonoBehaviour {
public Transform player;
public float walkSpeed = 10f;
// Use this for initialization
void Start ()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update ()
{
float translation = Input.GetAxis ("Vertical") * walkSpeed;
float straffe = Input.GetAxis ("Horizontal") * walkSpeed;
translation *= Time.deltaTime;
straffe *= Time.deltaTime;
transform.Translate(straffe, 0, translation);
if (Input.GetKeyDown (KeyCode.LeftControl))
this.transform.localScale -= new Vector3 (0f, 0.4f);
if (Input.GetKeyUp (KeyCode.LeftControl))
this.transform.localScale += new Vector3 (0f, 0.4f);
}
}
Answer by Xavier78 · May 08, 2018 at 04:38 AM
There are lots of tutorials about raycasting like, https://www.youtube.com/watch?v=6agwCUaMNWI My suggestion is to also have it ignore the player object. Here is something to get you started, really just check the distance, and make sure it isn't Hitting the player also.
Ray ray = new Ray(transform.position, Vector3.up);
RaycastHit Hit;
if (Physics.Raycast(ray, out Hit))
{
// We hit something above
float distanceUp = Vector3.Distance(transform.position, Hit.point);
}
It depends on when you want to do the check. If you want to do it every frame, put it in your update loop.
I personally would put it in the if statement of get key up. do the raycast first, and then if the distance is greater then the height change the local scale.
If his player is a capsule Collider and he is raycasting from the inside out, he does not need a layer mask. A raycast will not hit a Collider if the origin of the ray is inside that same Collider. If he has more than just a capsule, then he might have to worry about it, but in most cases for an fps, you don't.
Thank you for noting that @$$anonymous$$ciwsolb
Your answer
Follow this Question
Related Questions
Can you figure out raycast origin position from RacyastHit? 2 Answers
Vehicle is vibrating on the edge of the ramp/surface when I get the normal of the surface 0 Answers
how detect "OnRaycastOut" 1 Answer
Help with moving object towards player using Raycasting 1 Answer
raycast screenpointtoray isnt working for some reason 0 Answers