Auto Rotate to Enemies for Mobile Game?

Hi, I’m trying to understand scripting and I need ideas for how to do this. I want to make a button, when player press it, character will rotate to closest enemy and fire automatically. I know this is VERY HARD for a beginner, but I am learning with figuring out hard things. I just need idea, or a path how to do it, your thoughts will be enough for me. Thanks.

you really have three questions here, first how to find closest enemy, two how to rotate to face them, three how to fire your weapon. these things have been covered many times so ill just do a little overview here and provide an example of the difficult bits.

first is the finding the enemy and deciding which is closest. for this you will need to know avout the enemies to consider and this is up to you how to handle it, you could use overlaps, perception, or any number of other methods, here i used get all of class for simplicity. next you need a loop which considers all the possible enemies and figures out which is closest. in the example below i have a current closest enemy variable(A) and i compare its distance to the player to every other enemy(B). if the other enemy(B) is closer to the player than the closestcurrent (A), then the other enemy (B) gets set the be the closestcurrent (a). basically your just seeing is one closer to the player than the other if yes he becomes the closest. at the end you end up with the enemy thats closest to the player being the one set to the closest variable. its actually simpler than it sounds.

the next part is rotating the player to face the enemy. for this i used a timeline to set the rotation via a lerp, but you could also easily use a RInterp to node. if you use the timeline setup then the high points are that the timelines graph is a 0-1 value over X time where X is how ling you want the rotation to take (this is one of the limiting factors here, if you want a constant rotation speed then a Rinterp would be better). another thing to note here is the find look at rotation node, this is a easy way to find the rotation that the player needs to be looking to be facing the enemy. also when using a timeline you need two set values to lerp between otherwise it wont work correctly.

the last thing to cover would be the firing script but that will really depend on how you want it setup so i didnt make an example. for example do you want it to keep firing or only do it once? are you using a spawn projectile or a trace? theres alot to consider.

like i said though this is just a super simple example to get you started and show some of the basic theory on how things can be done.

1 Like