Player Behavior
Last updated
Last updated
At this point we have a ship which is visible on Screen, but it doesn't do anything. This tutorial adds behavior to our Player Entity so that it can move, turn, and shoot.
For this game, the Player will continuously move forward at a constant speed. The Player object will be turned left and right with the keyboard or Xbox gamepad. Before we begin writing any code we'll add two variables to Player: MovementSpeed and TurningSpeed. To do this:
Select the Player entity
Select the Variables tab
Click the Create a new variable button
Leave the defaults Create a new variable option and float type
Enter the name MovementSpeed
Click OK
Repeat the steps above to also add a TurningSpeed variable.
Next let's give the variables some default values:
Enter a value of 100 for MovementSpeed. This is the number of pixels the Player will travel in one second.
Enter a value of 3.14 for TurningSpeed. This is the maximum number of radians the Player will rotate in one second.
To apply movement we will need to write some C# code. To do this:
Open the project in Visual Studio (or switch to Visual Studio if you already have it open)
Open Player.cs. This is in the Entities folder in the Solution Explorer.
Scroll to the CustomActivity method in Player.cs
Modify CustomActivity as shown in the following snippet:
If you now run the game you will see the ship move upward, then eventually move off-screen.
If you are unfamiliar with the RotationMatrix property, or with matrices in general then you may be wondering about the RotationMatrix.Up variable, and why we're using it. The RotationMatrix property contains information about how an Entity, Sprite, or any other PositionedObject is rotated. The Up property indicates you which way is "up" for the object given its current rotation. This value is in "object space" meaning that if the object rotates, then this value will rotate along with the object. This is especially convenient for this tutorial because this game will have the ships always moving forward. The code above will work regardless of which way the Player is rotated - something which we'll see in the coming sections.
The next step is to assign input logic so the Player can turn. We will add an object to our Player representing the input device. This could be a gampad, keyboard, or any other object. By using the I1DInput interface, we can write the code the same regardless of the actual hardware used to control the Player. Modify Player.cs as shown in the following snippet: