Hi.
I’m trying to make a selection box for an rts. i’ve got the gui animations right, and figured out how to convert the screen coordinates (coordinaates of the box’ corners) to world coordinates on the terrain.
i’ve then made a boxcollider whith the coordinates. And it works well, but only for moving objects. Is there a way to detect objects that are standing still?
Here’s my code:
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
public class Selectionbox : MonoBehaviour {
Rect sbox = new Rect(100,100,1,1); //moves selected objects so i can identify them
List<GameObject>sobjects = new List<GameObject>();
short doSelect=0;
// Use this for initialization
void Start () {
}
void Awake() {
}
void Update()
{
if(doSelect>0)doSelect--;
foreach(GameObject go in sobjects)
{
go.transform.Translate(1,0,0);
}
}
// Update is called once per frame
void OnGUI () {
float mousex=Input.mousePosition.x;
float mousey=-Input.mousePosition.y+Screen.height;
if(Input.GetMouseButtonDown(0)){
sbox.x=mousex;
sbox.y=mousey;
}
if(Input.GetMouseButton(0))
{
sbox.width=mousex-sbox.x;
sbox.height=mousey-sbox.y;
GUI.Box(sbox, ""); //mystyle);
}
if(Input.GetMouseButtonUp(0)){
//raycasting goes here
Ray ray1 =Camera.main.ScreenPointToRay(new Vector3(sbox.x,-sbox.y+Screen.height));
Ray ray2 =Camera.main.ScreenPointToRay(new Vector3(mousex, Input.mousePosition.y));
//convert to world coordinates
RaycastHit hit1= new RaycastHit();
RaycastHit hit2= new RaycastHit();
Terrain.activeTerrain.collider.Raycast(ray1, out hit1, 5000.0f);
Terrain.activeTerrain.collider.Raycast(ray2, out hit2, 5000.0f);
transform.position=new Vector3((hit1.point.x+hit2.point.x)/2.0f, 0, (hit1.point.z+hit2.point.z)/2.0f);
transform.localScale=new Vector3(Mathf.Abs(hit2.point.x-hit1.point.x), 140, Mathf.Abs(hit2.point.z-hit1.point.z));
doSelect=2; //means the selection rutine runs once
}
}
void OnTriggerEnter(Collider other)
{
if(doSelect>0&other.GetComponent("Box"))
{
if(other.GetComponent<Box>().selectable)
{
other.GetComponent<Box>().selected=true;
}
sobjects.Add(other.gameObject);
}
}
}
any ideas?