• Availability

    I am currently available and taking on new projects.

Stencyl – Turn an actor slowly towards another

Making one actor point towards, or face another is a relatively easy affair. However, simply pointing an actor towards another is rather limited, and may not be what you’re after.

Why would you like to change the speed of rotation?

Being able to change the rate of speed at which one actor turns to face another is useful for a number of situations. Imagine a tower defence game where turrets turn to face enemies, a tank turret slowly rotating independently of the tank’s body, or even using it to turn a plane.


Open demo in a new window (You may need to enable pop-ups in order to view the demo.)

Arrows to move, Z to fire.

The Code

Let’s have a look at the code that used to achieve the effect.
This code is attached to the enemy plane as used in the above demo. When created, the first line creates the player actor. In this instance the player actor is created at a random location on the screen.

Secondly, an actor attribute is created using the player actor. This is so we can refer to it later.

Finally there’s a custom event. This is not relevant to the enemy movement, but I will touch on it at the end.

The code in this image is more complex, and it uses the Easy Math Extension, though it’s possible to get this working without it, you would just need to write the code to calculate the angle between the two actors yourself.

‘dA’ is a number attribute that you’d need to create. The ‘value of EnemyTurn’ is a value that’s stored in a map, and dictates the speed at which the actor turns. I’ve used a map value here so that I can change the value in-game. If you don’t need the value to change, you can put a number value directly in here. 1 is a good value. The higher the value, the faster the turn.

The last line simply points the actor in the right direction, and sets the velocity at which it is to move. This would be zero if you wanted it to be stationary.

This third image isn’t part of the actual movement behaviour, but I have used the ‘dA’ value for another purpose. These blocks make the enemy plane fire towards the player. So that the shooting isn’t random, the code checks the value of ‘dA’ and if the value is between -2 and +2, then the enemy will shoot towards the player. When ‘dA’ is zero, the player is in the direct line of sight.

Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *