Using Raycast to change position of a GameObject

Updated on August 6, 2018 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on August 4, 2018

I need to be able to “spawn” a wall shaped item (im really just changing the position of the Object)
Which isn’t a problem, I just put the object -10 Y below the ground until its needed.
I have a ‘working’ code that sets the items position to the camera’s position but i’d like it to be a few units in front of the camera as to avoid clipping issues and only aligning with the y rotation value instead of the x value and the y value.
Code   (C#):

 
using UnityEngine;
 
public class NanoWall : MonoBehaviour
{
 public float Range = 10f;
 
public Camera fpsCam;
 
void Start()
 {
 transform.position = new Vector3(0, -10, 0);
 }
 
void Update()
 {
 if (Input.GetKeyDown(KeyCode.F))
 {
 RaycastHit HitInfo;
 if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out HitInfo, Range))
 {
 transform.rotation = (fpsCam.transform.rotation);
 transform.position = (HitInfo.transform.position);
 }
 }
 }
}
 
 
How might I accomplish this?
Is there a better way to do it than how I have it?

  • Liked by
Reply
0 on August 6, 2018

What you have looks like it should work pretty good, unless you’re not looking below the horizon.

As for locking the X rotation, you could make a new rotation and just set the Y’s rotation so it ignores the X’s and Z’s.

transform.rotation = Quaternion.Euler(0, fpsCam.eulerAngles.y, 0);
  • Liked by
Reply
Cancel