- Home /
Raycast Hover
I have a ufo that hovers but I want to use raycast so the player can hide from it.. sadly I dont know that much can someone help me make it so that it only follows within the ray cast?
var verticalDistance : float; // distance above player to hover
var maxMovementSpeed : float; // units per second
var target : Transform; // transform to hover over
// JavaScript example.
function Update () {
// Bit shift the index of the layer (8) to get a bit mask
var layerMask = 1 << 11;
// This would cast rays only against colliders in layer 8.
// But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
layerMask = ~layerMask;
var hit : RaycastHit;
// Does the ray intersect any objects excluding the player layer
if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.down), hit, Mathf.Infinity, layerMask)) {
Debug.DrawRay (transform.position, transform.TransformDirection (Vector3.down) * hit.distance, Color.yellow);
print ("Did Hit");
} else {
Debug.DrawRay (transform.position, transform.TransformDirection (Vector3.downd) *1000, Color.white);
print ("Did not Hit");
}
}
function OnTriggerStay() {
var movement = target.position - transform.position;
movement.y -= verticalDistance;
// Move either at movement speed or directly to desired position, whichever's smaller. Prevents jittering hopefully.
transform.position += Vector3.Min( movement * Time.deltaTime, movement.normalized * maxMovementSpeed * Time.deltaTime );
}
I would not do this in Update()...
// Bit shift the index of the layer (8) to get a bit mask
var layer$$anonymous$$ask = 1 << 11;
// This would cast rays only against colliders in layer 8.
// But ins$$anonymous$$d we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
layer$$anonymous$$ask = ~layer$$anonymous$$ask;
as it seems needlessly complicated/repeated. Ins$$anonymous$$d, why not do this (add around line 3)
var layer$$anonymous$$ask : Layer$$anonymous$$ask;
which will expose a simple dropdown button in the Editor that you can use to check/uncheck the layers the Raycast interacts with.
I think what you want the UFO to do is the code in the OnTrigger, so move that into the if(Raycast) block.
Your answer
Follow this Question
Related Questions
rotating hovercar to be at the same angle as the terrain/object below it 1 Answer
Make camera hover at 50 over hilly terrain 2 Answers
Jittery Movement 3 Answers
Aligning player to surface 2 Answers