- Home /
Raycast and First Person Controller
Hi!
New to game programming and Unity 3D and i am now stuck with my project.
I have a "Plain" on my floor with a blood texture. When my character looks down on it a GUI text will be shown. My idea was to assign this script to the Main Camera in the First Person Controller prefab:
function Update () {
var forward = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(tranform.position, forward, 10))
{
Debug.Log('Hit');
}
}
But it doesn´t work! Complaining about a transform issue. Why? I have draged my script to the Main Camera in the prefab and it has been assigned. So what is wrong? The Main Camera has Transform values so why can´t i access them?
Answer by ScroodgeM · Jul 22, 2012 at 07:58 AM
- frist
transform.TransformDirection(Vector3.forward);
is same astransform.forward;
second: didn't you forget assign a collider to plain? raycasts calculates on colliders, not on geometry
third: your character i think looks always in horizontal direction. look up and down causes camera to turn, but not character. so when you look down making 'transform.forward' from character's transform will return a horizontal direction
fourth: format your code, good formatted questions are more often gets answered
additive edit
using UnityEngine; using System.Collections; public class RayCaster : MonoBehaviour { bool iLookAtSomething = false; void OnGUI() { if (iLookAtSomething) { GUI.Label(new Rect(5, 5, 200, 30), "i look at something"); } } void Update() { RaycastHit hit; if (Physics.Raycast(transform.position, transform.forward, out hit, 10f, -1)) { iLookAtSomething = true; //do here whatever you want while looking at something } else { iLookAtSomething = false; } } }
attach this script to camera and whenever something with collider will be before the camera at minimal distance 10 meters - you got a message on the screen about it
Thx for the code example. $$anonymous$$anaged to solve it by looking at your code and doing it in Javascript with some tweaking.
Answer by Frankiej · Jul 22, 2012 at 10:02 AM
Thanx for your answer.
Didn´t know that. I´m new my code was from this video: http://www.youtube.com/watch?v=-F_w3RDRbN4&list=PL27B696FB515608D2∈dex=33&feature=plpp_video
Yes, there is no collider on the plain. Didn´t add that because i wanted the raycast to been functional before i did that.
You´re right. That´s why i tried to assign my code to the camera. I´m guessing i have to tweek it.
Did that. Thx for the tip.
Still i´m stuck. How could i solve it. And why does Unity complain about me using just transform? Even if i know i can´t use the transform code to solve my mouse viewing raycast i´m curious why my code doesn´t work at all.
Your answer
Follow this Question
Related Questions
Raycast misses after camera zoom 2 Answers
Camera to aim at raycast 1 Answer
Only show GameObject if at least 1 pixel is rendered 0 Answers
Follow mouse cursor (with Y = 0)? 1 Answer
Raycast to ignore collider ? 0 Answers