- Home /
Raycast check?
I am trying to create a lazer hit script that will tell the player that he is hit by the lazer. I am using the SendMessage called from the OutputLazer script when player intercepts the lazer. Before using this, i was using e boolean, that would set to true whe player intersect the lazer and flase when they do not. This worked untill you introduce 2 lazer outputs, becouse one of them will always say the player is not touching the lazer thus setting the boolean to false even if the other lazer is being intercepted.
I wish you could test if the player is being hit by a raycast from an object with a specific tag, that way all of this could be simplified to say if player is hit by raycast from this type of object, run this. But as far as i know thats not possible :(
I have been at it for 3 hours now and i just cant figure out a way to do it... i feel like im stupid... please help me.
here is the code for the OutputLazer script:
// Update is called once per frame
void Update () {
//If lazer is on, test for any objects in the way
if(lazerOn){
if(Physics.Raycast(transform.position, -transform.forward, out hit)){
//Execute lazer collision when intersecting object has a collider
if(hit.collider){
LazerCollision();
}
} else {
LazerNoCollision();
}
}
}
//Called when lazer hits a collider
void LazerCollision (){
lr.SetPosition(1, new Vector3(0,0,-hit.distance));
//If lazer hits player, tell player they are in a lazer
if(hit.collider.tag == "Player"){
playerScript.SendMessage("InLazer");
}
}
//Called when lazer hits nothing
void LazerNoCollision(){
lr.SetPosition(1, new Vector3(0,0,-50));
}
Here are the snips of the code the Player script has containing the lazer portions:
// Update is called once per frame
void Update () {
//Check if Player is falling off the map
if (transform.position.y < 0.2){
Die();
}
//Imitate player cooling down is player if hot
if(rndr.material.color != playerColor){
rndr.material.color = Color.Lerp(rndr.material.color, playerColor, Time.deltaTime * colorSmooth);
}
//If timer is above 0, decrease timer by seconds
if(dieTimer > 0){
dieTimer -= Time.deltaTime;
}
}
//Runs when intersecting a lazer
void InLazer(){
//Imitate player heating up
rndr.material.color = Color.Lerp(rndr.material.color, heatColor, Time.deltaTime * colorSmooth);
//Increment death timer
dieTimer += Time.deltaTime;
LazerDeathCounter();
}
//Kills player and resets lazer values / player color
void LazerDeathCounter(){
if(dieTimer >= 0.5f){
Die();
rndr.material.color = playerColor;
dieTimer = 0;
}
}
The raycasting object performs the check against what was hit by the raycast. It is easy enough to communicate with the hit object by interacting with the RaycastHHit info. There is much information on this.
Your answer
![](https://koobas.hobune.stream/wayback/20220613185751im_/https://answers.unity.com/themes/thub/images/avi.jpg)