Raycast positioning problem
Hi, I'm trying to debug.log :"Position available" when the player looks at an object that is 5 or less units away. I'm having an issue with my raycast's origin and direction though: they don't start anywhere near my player gameobject (at least not by the looks of my debug.drawray) and "position available" is never output by the console. Here is my code:
using UnityEngine;
using System.Collections;
public class Phase1 : MonoBehaviour
{
private float DistanceToPosition = 5;
public void Positioning ()
{
RaycastHit hit;
Ray PositioningRay = new Ray(transform.position, transform.forward);
if (Input.GetButtonDown("Fire1"))
{
Debug.DrawRay(gameObject.transform.position, gameObject.transform.forward * DistanceToPosition);
if (Physics.Raycast(PositioningRay, out hit, DistanceToPosition))
{
if (hit.distance < DistanceToPosition)
{
Debug.Log("PositionAvailable");
}
}
}
}
}
By the way the function is called from another script. I'd greatly appreciate any help.
If I'm not mistaken, Input.GetButtonDown is only available within Update and FixedUpdate.
Debug.DrawRay does appear, just not at the correct position, so the if statement has got to be correct I think (correct me if I'm missing something, I'm a beginner).
Answer by ahungrybear · Dec 29, 2016 at 08:53 PM
Hmmm. The code itself look fine... (I'm assuming the script is attached to the player)
Where is the ray starting relative to your character?
Also you don't need gameObject.transform.position, just transform.position is fine
Yeah, the script is attached to the player. The ray's position doesn't change relative to my character's position, the transform position is : (4.1, 1.0, -2.2) where as the player spawns at (-6.88, 0.1, -6.56). There's also no other gameobject or script referencing that position which completely confuses me.
Hmmm. Yeah it seems like you've got a good problem on your hands. When is this function called btw? Is it continuous? Also could you share a screenshot of your scene? I can't seem to find anything wrong with the script on my end.
the function is called from the following script which is on the Game$$anonymous$$anager object you can see in the pic below:
using UnityEngine;
using System.Collections;
public class Phase : $$anonymous$$onoBehaviour
{
public int TimeLeft = 60;
public GameObject ScriptAttachedTo;
void Start()
{
InvokeRepeating("PreparationPhase",0,1);
}
void Update()
{
if (TimeLeft > 0)
{
ScriptAttachedTo.GetComponent<Phase1>().Positioning();
}
}
void PreparationPhase()
{
Debug.Log(TimeLeft);
TimeLeft -= 1;
if(TimeLeft == 0)
{
Debug.Log("End of Preparation Phase");
CancelInvoke();
}
}
}
so yeah, it is continuous. Here is a screenshot of my scene (networked so the player prefab isn't spawned in):