I am trying to make an object move to an endpoint of a raytrace going forward from the player each time I press a key.
playerViewport = gameObject.Find("Main Camera");
private var player : Transform;
player = playerViewport.transform;
function Update () {
var holdRaycast : RaycastHit;
Physics.Raycast(player.position, player.forward, holdRaycast, 1);
Debug.DrawRay(player.position, player.forward*1, Color.yellow);
if(pressed){
if(!raycastTriggered){
}
raycastTriggered = true;
transform.position = holdRaycast.point;
print(holdRaycast.point);
}
if(Input.GetButtonUp("Use")){
pressed = false;
raycastTriggered = false;
}
else if(Input.GetButtonDown("Use")){
pressed = true;
gameObject.Find("GameHandler").SendMessage("hideUse");
}
}
Every time I do so however the returned position of the holdRaycast.point is (0,0,0). The ray isn’t actualy colliding with anything as it is only for getting a position where the player can place the object.
It would be much appreciated if someone could point out what I am doing wrong.
RayTrace will only return a value if it is hitting something.
I think this would be a simplified version of your code. Notice the if statement contains the raytrace.
playerViewport = gameObject.Find("Main Camera");
private var player : Transform;
player = playerViewport.transform;
function Update ()
{
if(Input.GetButtonDown("Use"))
{
var holdRaycast : RaycastHit;
if (Physics.Raycast(player.position, player.forward, holdRaycast, 1))
{
transform.position = holdRaycast.point;
}
Debug.DrawRay(player.position, player.forward*1, Color.yellow);
gameObject.Find("GameHandler").SendMessage("hideUse");
}
}
However, I don’t think this is what you want. If you just want the object to appear 1 unit in front the player floating, do something like this:
playerViewport = gameObject.Find("Main Camera");
private var player : Transform;
player = playerViewport.transform;
var distance : float = 1;
function Update ()
{
if(Input.GetButtonDown("Use"))
{
transform.position = Transform.TransformPoint( player.forward * distance );
Debug.DrawRay(player.position, player.forward*1, Color.yellow);
gameObject.Find("GameHandler").SendMessage("hideUse");
}
}
I think this will work but I’m not at home to try it.
The third option:
playerViewport = gameObject.Find("Main Camera");
var distance : float = 1;
private var objectHeld : GameObject;
function Update ()
{
if(Input.GetButtonDown("Use"))
{
if (!isHeld)
{
if (Physics.Raycast(transform.position, transform.forward, holdRaycast, 1))
{
objectHeld = holdRaycast.collider;
isHeld = true;
}
}
else isHeld = false;
gameObject.Find("GameHandler").SendMessage("hideUse");
}
if (isHeld)
{
objectHeld.transform.position = Transform.TransformPoint( transform.forward * distance );
}
}