- Home /
Question by
galaboy · Feb 11, 2019 at 10:49 AM ·
raycastraycasthitreflect
How to reflect raycast when hit an object.
Hi, i tried to reflect a raycast when hit an object. The limit of the raycast hit has to be 3. I tried searching, but could able to find. i am positng my script here, please have a look and tell what i am missing.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Laser_1 : MonoBehaviour {
public int maxHitCount = 3;
public int rayMaxDistance = 0;
private int hitCount = 0;
public Vector3 startingPosition;
private Vector3 direction;
LineRenderer laserRenderer;
// Use this for initialization
void Start () {
laserRenderer = GetComponent<LineRenderer>();
//startingPosition = transform.position;
}
// Update is called once per frame
void Update () {
ProjectTrajectory();
}
void ProjectTrajectory()
{
Ray ray = new Ray(startingPosition, direction);
RaycastHit hit;
laserRenderer.SetPosition(0, new Vector3(0, 0, transform.position.z));
//Debug.Log("The hit count outside if is : " + hitCount);
//if (Physics.Raycast(ray, out hit, rayMaxDistance))
if (Physics.Raycast(transform.position, transform.forward, out hit, rayMaxDistance))
//if (Physics.Raycast(transform.position, direction, out hit, rayMaxDistance))
{
startingPosition = hit.point;
laserRenderer.SetPosition(1, hit.point);
direction = Vector3.Reflect(direction, hit.normal);
//direction = Vector3.Reflect(hit.point - transform.position, hit.normal);
}
else
{
//Debug.DrawLine(transform.position, (transform.forward * rayMaxDistance), Color.red);
//laserRenderer.SetPosition(0, new Vector3(0, 0, transform.position.z));
laserRenderer.SetPosition(1, transform.forward * rayMaxDistance);
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612191525im_/https://answers.unity.com/themes/thub/images/avi.jpg)