- Home /
Why Does the Ray change my object position?
Hello. I am following the laser beam tutorial in the videos of the Learn section.
However, when I try to implement the lasers something strange happens, when I shoot my lasers the gun tip changes its position, the laser appears in the new position and slowly moves away. I tried to keep in the position I am setting it to, but it keeps changing its position and then moving away.
Here is the code I am using. I will be thankful for any kind of help.
using UnityEngine;
using System.Collections;
public class OverWeapon : MonoBehaviour
{
LineRenderer line;
//public Transform rifleGun;
void Start()
{
line = gameObject.GetComponent<LineRenderer>();
line.enabled = false;
}
void Update()
{
Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
Debug.DrawRay(transform.position, -forward, Color.green);
if(Input.GetKeyDown(KeyCode.Space))
{
StopCoroutine("shootBeam");
StartCoroutine("shootBeam");
}
}
IEnumerator shootBeam()
{
line.enabled = true;
while(Input.GetKey(KeyCode.Space))
{
//Ray ray = new Ray(transform.position, transform.forward);//I HAVE DISCOVERED THAT THIS IS SOMEHOW CAUSING THE PROBLEM
line.SetPosition(0,ray.origin);
line.SetPosition(1,ray.GetPoint(100));
yield return null;
}
line.enabled = false;
}
}
Answer by Kiloblargh · Dec 19, 2013 at 12:52 AM
I'm not sure if this is the problem, but you shouldn't use a while loop that way.
And your code has a lot of redundancy in it. Try this:
Update() {
line.enabled = Input.GetKey (KeyCode.Space) );
if (line.enabled) {
line.SetPosition (0, transform.position);
line.SetPosition (1, transform.TransformPoint (Vector3(0,0,100)));
}
Alright I will give it a try. However, I am trying to use a ray as I draw my line because I want my laser to eventually hit something and destroy it. Now, the reason I used that while loop is that I was trying to practice on coroutines. Please do excuse my horrible coding and thanks for your help. :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613124444im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to set position of raycast higher? 1 Answer
Performance issue Raycast each frame 1 Answer
Changing position of a RayCast 1 Answer
Using Trigonometry for Collision Detection 0 Answers
how to tell what platform you're on. 1 Answer