- Home /
Android Button With Raycast
I just wonder if I can get a little help here, I need a few directions on how I will start with making buttons on an android platform with raycast - this is the script I got but how the hell will I make it work? do I just add raycast collider to the 3d text and add this script and it will work or how do I do?
var particle : GameObject;
function Update () {
if (Input.GetButtonDown ("Fire1")) {
// Construct a ray from the current mouse coordinates
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray)) {
// Create a particle if hit
Instantiate (particle, transform.position, transform.rotation);
Application.LoadLevel(0);
}
}
}
Answer by KureFlint · Sep 22, 2011 at 01:08 AM
If your making buttons for a mobile platform don't use raycasts. Use GUI. Or, and Highly recomend it, use Rect.Contains as a means of reaplacing GUI.
Here's an example of how it would look.
//variables which construct the Rectangle
var Rect = Rect(Screen.width,Screen.height,Screen.width,Screen.height);
var HorizontalPositionx : float;
var VerticalPositiony : float;
var Width : float;
var Height : float;
var custom : GUIStyle;
function Update(){
Rect.y = Screen.height/VerticalPositiony;
Rect.x = Screen.width/HorizontalPositionx;
Rect.height = Screen.height/Height;
Rect.width = Screen.width/Width;
if (Rect.Contains(Input.mousePosition)){
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began){
// Create a particle if hit
Instantiate (particle, transform.position, transform.rotation);
Application.LoadLevel(0);
}
}
//you can edit this to show whatever your button is later but for now this just shows where your rect is
function OnGUI(){
GUI.Box(Rect, "Button Rect", custom);
}
That just means I forgot to put a semicolon in there somewhere and that i forgot a bracket. I typed it up and the spot just to show you how it could be done so you could write your own, I didn't actually test it. Just put an extra bracket after Application.LoadLevel(0); and find where I forgot the semicolon. Also, add var particle : GameObject in the beginning if you don't already have it. Then it'll work.
Good Luck.
Answer by 1337GameDev · Nov 07, 2011 at 09:59 PM
When programming for mobile devices, i am told that using unity OnGui is very processor intensive (as it has calls every frame) but to use a raycast or rectangle.contains instead.
Answer by ICEF1SCH · Aug 13, 2012 at 09:13 AM
Here's what I've got : (It is in C# but I think it should be easy to convert!)
void Update() {
if (Input.GetButtonDown ("Melee")) { Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { if (hit.transform == transform){ Application.LoadLevel(0); } } }
}
You need to add a RaycastHit to know that the button was hit!