raycasting doesn't work
I'm using a raycast to find the tags of objects so that i can chop down trees and pick things up etc, but the ray cast only works if im at 6 feet away and that makes the game quite un-enjoyable. Please help.
Then where is your CODE ... how on this earth i will get to know whether you've set the maximum ray distance to 6 feet or not
using UnityEngine;
using System.Collections;
public class cQA : $$anonymous$$onoBehaviour {
private GameObject pC;
private GameObject player;
private playerAction pA;
// Use this for initialization
void Start () {
pC = GameObject.Find ("playerCamera");
player = GameObject.Find ("FPSController");
pA = player.GetComponent<playerAction> ();
}
public void checkIfHitting() {
RaycastHit hit;
Ray meleePath = new Ray (pC.transform.position, pC.transform.forward);
Debug.DrawRay (transform.position, transform.forward* 2);
if (Input.GetButtonDown ("Fire2")) {
if (Physics.Raycast (meleePath, out hit, 2)) {
if (hit.collider.tag == "pTF") {
pTF ptf = hit.collider.GetComponent<pTF> ();
ptf.chopTree (pA.getD$$anonymous$$G ());
}
if (hit.collider.tag == "pTHO") {
pTHO ptho = hit.collider.GetComponent<pTHO> ();
ptho.chopTree (pA.getD$$anonymous$$G ());
}
if (hit.collider.tag == "pTHT") {
pTHT ptht = hit.collider.GetComponent<pTHT> ();
ptht.chopTree (pA.getD$$anonymous$$G ());
}
if (hit.collider.tag == "pileOS") {
Debug.Log ("sticks");
pileOS pileos = hit.collider.GetComponent<pileOS> ();
pileos.collectSticks ();
}
}
}
if (Input.GetButtonDown ("Fire1")) {
if (Physics.Raycast (meleePath, out hit, 3)) {
if (hit.collider.tag == "pileOS") {
Debug.Log ("sticks");
pileOS pileos = hit.collider.GetComponent<pileOS> ();
pileos.collectSticks ();
}
}
}
}
// Update is called once per frame
void Update () {
checkIfHitting ();
}
}
Answer by aditya · Aug 22, 2016 at 08:14 AM
try this
Ray ray = Camera.main.ScreenPointToRay(new Vector2(0f,0f));
if(Physics.RayCast(ray, out hit, 2f)){
// Do your stuff here
}
i m assuming that you have only one camera in scene
if you are not casting ray from camera then what is this variable pC
... isn't it a Camera ?
Yes haha I realized that after i said it, Thanks!
Your answer
Follow this Question
Related Questions
Raycast is going through collider (A plane) 0 Answers
How would I project a Gameobject onto the surface of another? 0 Answers
Turning off a script when Raycast leaves object 1 Answer
Accessing Raycast collider from another script 0 Answers
Switching from object to object with Raycast Problem 1 Answer