Yo fellow game developers!
So recently gamedev became my favorite hobby and I started working on my RTS game module which would then let me create different RTS games with just few changes (W3 inpiration :3). Anyway I am new to optimalization since my previous games had quite serious optimalization issues so I need your help with a pieace of code!
I am having a mass selection of units with drawn rectangle on screen. I've got it all worked out but now I am wondering if there could be anything done about optimalization for cycling through list of units every time my mouse position changes even for a little bit.
This is inside my Update function. There is much more in there so i cut it out but this is the piece I am worried about:
void Update(){
//...previous code blah blah blah...
if (Input.GetMouseButton(0)) {
oldPos2 = point2;
point2 = Input.mousePosition;
if (oldPos2!=point2) {//performance optimalization
Debug.Log ("Performing selection");
if (Vector2.Distance(point1,point2) >= selBoxIniDist) {
isSelecting = true;
foreach (var item in Game.Units) {
if (IsWithinSelectionBounds (item.gameObject)) {
item.Selected = true;
} else {
item.Selected = false;
}
}
}
}
}
//...rest of the code here...
}
So as i told you, there is no problem with the code. I just need your opinion if there could be any changes especialy to this part of the code. Or maybe general advices for optimalization.
Even tho I am checking every update if the mouse moved (so I dont cycle every update) I still feel like checking every "milimeter" 5 times if any of the units are contained in the viewport rectangle is a little bit overkill just for the selecting units. At the end of selection I usualy end up with around less than 100 cycles.
What do you think?
EDIT: I might as well add a method that checks if the unit is in the viewport bounds and a utility method that calculate the bounds. Just so you why I am worried about performance.
Checking if bounds contain unit:
public bool IsWithinSelectionBounds( GameObject gameObject )
{
if (!isSelecting) {
return false;
}
var camera = Camera.main;
var viewportBounds = Utilities.GetViewportBounds( camera, point1, point2);
return viewportBounds.Contains(camera.WorldToViewportPoint(gameObject.transform.position));
}
Static utilities:
public static Bounds GetViewportBounds( Camera camera, Vector2 screenPosition1, Vector2 screenPosition2 )
{
var cam = Camera.main;
var v1 = cam.ScreenToViewportPoint( screenPosition1 );
var v2 = cam.ScreenToViewportPoint( screenPosition2 );
var min = Vector3.Min( v1, v2 );
var max = Vector3.Max( v1, v2 );
min.z = camera.nearClipPlane;
max.z = camera.farClipPlane;
var bounds = new Bounds();
bounds.SetMinMax( min, max );
return bounds;
}