- Home /
Raycast hits both objects
Ok, here we go. I have a tiled map for my game. It consists of a couple of boxes, that must elevate on raycast. The question is: How do i stop the ray when it hits any box of my map? The code below is attached to each of the tiles. Is there a better way to achieve my requirements?
C#:
using UnityEngine;
using System.Collections;
public class TileOnMouseOver : MonoBehaviour
{
public float deltaHeight = 0.1f;
public Color customCol;
Color normalCol;
Vector3 normalTransform;
bool once = true;
// Use this for initialization
void Start()
{
normalCol = renderer.material.color;
normalTransform = transform.position;
}
// Update is called once per frame
void Update()
{
Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (collider.Raycast(ray, out hitInfo, Mathf.Infinity))
{
if (once)
{
Vector3 deltaVect = transform.position;
deltaVect.y += deltaHeight;
renderer.material.color = customCol;
transform.position = deltaVect;
once = false;
}
}
else
{
renderer.material.color = normalCol;
transform.position = normalTransform;
once = true;
}
}
}
And some screenshots to clarify my question:
(The upper tile blinks)
Answer by MakeCodeNow · Feb 15, 2014 at 08:44 PM
You should make a single Controller type component (probably put it on your MainCamera) and then use Physics.Raycast. That will be cheaper (only one raycast per frame instead of one raycast per tile) and it will, by default, stop at the first thing it collided with. Your controller can then call a function on the hit TileOnMouseOver that let's it know that the cursor is over it right now.
Your answer
Follow this Question
Related Questions
Detect Mouse in right side or left side For Player? 2 Answers
How to achieve a more accurate Mouse to WorldCoordinates & faster updating of object follow? 2 Answers
Raycast not detecting ANY HITS AT ALL when starting inside a collider. 0 Answers