- Home /
Raycast question
So ive made a grid out of cubes with two seperate scripts attached to it. One to highlight the cube by changing its color, the other is a raycast 1.0 high going up. what im wondering is how to i make a non rigid body cube spawn at the top of the point of the raycast.
code for Raycast:
using UnityEngine;
using System.Collections;
public class CubeRaycast : MonoBehaviour {
public RaycastHit hit;
public GameObject Cube;
public float range = 1.0F;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 DirectionRay = transform.TransformDirection(Vector3.up);
Debug.DrawRay(transform.position, DirectionRay * range, Color.red);
if (Physics.Raycast(transform.position, transform.up, out hit, 1F))
{
if(Input.GetKeyDown(KeyCode.Mouse0)){
range += 1.0F;
GameObject instanceCube = Instantiate(Cube,hit.point,transform.rotation)as GameObject;
}
}
}
}
What and where is the object the Physics.Raycast is supposed to hit?
I mean there is a difference between DrawRay and Physics.Raycast and Physics.Raycast will not return true if aimed at infinity.
That can also be achieved without raycast, on the square level with use of on$$anonymous$$ouseDown, on$$anonymous$$ouseOver and on$$anonymous$$ouseExit functions.
Not if you want to run on mobile. And i think on those events raycast happens in background anyways.
That is right @Lovrenc, on$$anonymous$$ouseDown... have alternatives for mobiles, which in fact move us back to rays.
Answer by Lovrenc · Jan 13, 2013 at 04:11 PM
Once again. DrawRay and Raycast are two different things. The first is used for debugging, the other actually does the job. They work gret together for visualizing your ray but only if you set them up correctly to point in same direction.
In your code you have:
Debug.DrawRay(transform.position, DirectionRay * range, Color.red);
Physics.Raycast(transform.position, transform.up, out hit, 1F))
So you are drawing a ray in "DirectionRay" direction, but you are raycasting up the y axis of the object your script is in. Do:
Physics.Raycast(transform.position, DirectionRay , out hit, range))
This way you can visualize your ray. Your instantiation code looks ok.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How can i make the ray cast don't go through the walls 1 Answer
unknown identifer explosion problem 2 Answers
Glass break effect 2 Answers