- Home /
Calculate x units forward?
Here's a link to the game, so you can see what's going on.
Here's my object Heirarchy:
Simply put, what I'm trying to do is have a laser shoot 10 units away from the player Mesh. If the player stays at (0,0,0), no problems. For some reason, the moment I move, the second vertex in the lineRenderer seems to stay in the same spot. Any clues?
using UnityEngine;
using System.Collections;
public class Bangbang : MonoBehaviour {
RaycastHit hit;
Ray ray;
LineRenderer lr;
Transform GunPos;
Transform Player;
public Vector3 forwardpos;
void Start () {
lr = GetComponent<LineRenderer>();
GunPos = transform.Find("Gun");
Player = GameObject.Find ("PlayerMesh").transform;
forwardpos.z = transform.forward.z * 10;
forwardpos.x = transform.forward.x * 10;
}
void Update ()
{
forwardpos.z = transform.forward.z * 10;
forwardpos.x = transform.forward.x * 10;
if(Input.GetKey(KeyCode.Space))
{
lr.enabled = true;
lr.SetPosition(0, GunPos.position);
lr.SetPosition(1, forwardpos);
if(Physics.Raycast(GunPos.position, transform.forward, out hit, 10.0f))
{
lr.SetPosition(1, hit.point);
Debug.DrawLine(GunPos.position, hit.point);
}
Debug.DrawLine(GunPos.position, forwardpos);
}
else lr.enabled = false;
}
}
Answer by fafase · Apr 01, 2013 at 10:46 PM
transform.forward is a unit vector meaning it is equal to (0,0,1) that is why you always get the same position, you would have to convert it to world position.
I would go for:
forwardpos = transform.position + transform.forward*10;
Almost. This:
transform.TransformDirection(transform.forward*10);
doesn't make much sense ;) transform.forward is already a direction in worldspace. You treat it like a local space direction and transform it again into worldspace which would be quite rubbish.
transform.forward is the same as:
transform.TransformDirection(Vector3.forward);
Vector3.forward is a constant which equals 0,0,1. transform.forward is the objects forward vector in worldspace.
So it should be simply:
forwardpos = transform.position + transform.forward*10;
Oh yeah, my bad...even the doc starts with "The blue axis of the transform in world space."...
lol you might want to get rid of the old one. But thanks, that worked perfectly!
Answer by Nidre · Apr 01, 2013 at 09:01 PM
I cant be sure without seeing your object hierarchy but i presume that GunPos object is not a child of the mesh which is moving since you are calling GameObject.Find.
So are you sure GunPos object is also moving when player is moving ? Because u are using this objects position as start point for line renderer.
I would suggest adding GunPos object as child of player so it would always move with player.
Updated my question with my object Heirarchy. The first position for the line renderer is following my Player$$anonymous$$esh object, but for whatever reason the second position is not being updated properly.