- Home /
How to detect if a GUI texture is over an object
I am making a shooting game and I had a GUI texture to show what the player is aiming at (If this doesn't make sense, here is a picture:). I want it so then if the player is aiming at an enemy, the game would detect it and let the player take health out of the enemy. How could I do this (please in JavaScript)?
Are you talking about a GUITexture or are you drawing using GUI.DrawTexture()? Is the position the mouse position, or something else? If it is a GUITexture, do you have the PixelInset set so that the cross is at the center of the position? Are you trying to blind fire a particular direction, or do you have object that you want to target?
I'm talking about a GUITexture. The Pixel Inset is X=0, Y=0, Width=20, Height=20. That makes it about centered. When the player shoots, there isn't actually a bullet being cloned in the scene. What I want is if the GUITexture is over an enemy, it will take health out.
Answer by robertbu · Aug 16, 2013 at 03:01 PM
Assuming your cross is centered in the graphic, you will want to set your Pixel Inset to 10 and 10. This will anchor the center of the cross at the GUITexture position. To detect enemies you will use raycasting. GUITextures live in Viewport space, so you can create a ray from the position. I don't have you code nor know your game mechanic, so you will need to adjust this script for your game. It fires on a left mouse click. If it finds an enemy under the cursor (a game object tagged 'Enemy', it get the enemy health component from the enemy object and calls 'ApplyDamage()'.
#pragma strict
function Update() {
if (Input.GetMouseButtonDown(0)) {
var ray = Camera.main.ViewportPointToRay(transform.position);
var hit : RaycastHit;
if (Physics.Raycast(ray, hit)){
if (hit.collider.tag == "Enemy") {
var enemyScript = hit.collider.gameObject.GetComponent(EnemyHealth);
enemyScript.ApplyDamage();
}
}
}
}
Your answer

Follow this Question
Related Questions
Detect GUI rotation degree 1 Answer
transform.TransformDirection not working -- WHAT IM MISSISNG? 1 Answer
how do i make my own GUI 1 Answer
2D Aiming and Shooting at the mouse 3 Answers