I’m working on an overhead tower defence game, I have prefab towers setup that shoot at the creeps etc, and I have a piece of code for putting the towers onto the surface of the map, I’m getting there.
I just have 2 questions:
Which of these pieces of code is faster, and why? (I’m a self taught n00b)
SpawnPoint = Vector3 (hit.point.x, hit.point.y+2.5, hit.point.z);
or
SpawnPoint = hit.point + Vector3(0,2.5,0);
Also,
When I’m placing the towers they can overlap, which would be a better way to stop that - using a Physics.OverlapSphere to check for nearby towers or keeping an array or list of tower positions and checking against that ?
Any help is much appreciated.
First Question:
- Yes it is going to be faster to run the first piece of code, but the gain in performance is so small that unless you are doing that operation 10 times per frame, you will not notice a difference. Because the performance gain is negligible, I believe you are better off going with the second version because it is 1) simpler to read, and 2) it is easier to modify in the future.
Second Question:
- Using a Physics.OverlapSphere is a VERY expensive operation for the processor, but it is simple to code and uses very little memory space.
- Storeing the towers in an array is a relatively cheap operation for the processor, but it is complex to code, bug-prone, and uses a large amount of memory space.
If you are confident in your ability as a programmer and your ability to debug, then go with the second option. Otherwise, go with the first one because as long as you are only checking every once in a while (on user input, not every frame), the performance spike should not be too much of a problem.
Also, if your tower’s colliders are standardized (all of them are square and the exact size of the space they are being placed on), then it will be MUCH faster to simply perform a Physics.Raycast at the center of your proposed tower. If you can use a Raycast instead of a SphereCast, then the performance values will be close enough together that you should not have to worry about the complexities of using an array.
logty
3
I am pretty sure that for your first question, the first option is faster because it is only one Vector3 operation while the second one includes creating a vector3 and then adding it to another vector3, and on your second question the array is most likely faster (although if you are keeping it relitavely uncomplicated spherecast may be simpler), hope this helps!