Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Lerping to Raycast Point

Discussion in 'Scripting' started by SolarFalcon, Aug 13, 2019.

  1. SolarFalcon

    SolarFalcon

    Joined:
    Nov 28, 2015
    Posts:
    170
    Hello :)

    I have a script attached as a child to my third person camera. When a bool is set to true, it activates a particle effect and starts raycasting from the transform position down its forward direction. I'm using a LayerMask to denote what layers are ok to Raycast on, but whenever the camera is pointed away from the ground, the effect doesn't stay on the ground, it follows the lastGood position.

    I want the lastGood position to remain on the last point that is in the LayerMask. What am I doing wrong?

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class CastAtPoint : MonoBehaviour
    4. {
    5.     public Transform caster;
    6.     public float range;
    7.     public ParticleSystem pointEffect;
    8.     public LayerMask castLayer;
    9.     public Transform castPoint, lastGood;
    10.     RaycastHit rayHit;
    11.     public bool on = false;
    12.  
    13.     private void Start()
    14.     {
    15.         castPoint = GameObject.Find("Player Cast Point").transform;
    16.         pointEffect = castPoint.GetComponent<ParticleSystem>();
    17.     }
    18.  
    19.     private void Update()
    20.     {
    21.         if (on)
    22.         {
    23.             if (!pointEffect.isPlaying)
    24.             {
    25.                 pointEffect.Play();
    26.             }
    27.  
    28.             castPoint.position = Vector3.Lerp(castPoint.position, lastGood.position, Chronos.Timekeeper.instance.Clock("All").deltaTime * 10f);
    29.         }
    30.  
    31.         if (!on)
    32.         {
    33.             if (pointEffect.isPlaying)
    34.             {
    35.                 pointEffect.Stop();
    36.             }
    37.         }
    38.     }
    39.  
    40.     private void FixedUpdate()
    41.     {
    42.  
    43.         if(Physics.Raycast(transform.position, transform.forward, out rayHit, range, castLayer))
    44.         {
    45.             lastGood.position = rayHit.point;
    46.         }
    47.     }
    48. }
    49.  
     
  2. SolarFalcon

    SolarFalcon

    Joined:
    Nov 28, 2015
    Posts:
    170
    Uhh never mind, it seems the lastGood point was a child of the camera. :oops: