Player Movement

The next step is to add controls so the player can move the ball by pressing keys on their keyboard. We will use the Window:KeyDown() function to check if a key is pressed, and if it is we will apply a force to the ball. Enter this code into your custom script:
function Script:Start()
--Create a camera
self.camera = Camera:Create()
--Update the camera
self:UpdateCamera()
end

--Adjust the camera orientation relative to the ball
function Script:UpdateCamera()
self.camera:SetRotation(45,0,0)
self.camera:SetPosition(self.entity:GetPosition())
self.camera:Move(0,0,-4)
end

function Script:UpdatePhysics()
--Get the game window
local window = Window:GetCurrent()
--If the 'W' key is pressed add a force to the entity
if window:KeyDown(Key.W) then
self.entity:AddForce(0,0,10,true)
end
end

function Script:UpdateWorld()
--Update the camera each frame
self:UpdateCamera()
end

Run the game, and you will be able to control the ball by pressing the W key. In fact, you can send it right over the edge into space!

Of course, we want to be able to move our ball in all directions, so let's add some more code to handle that: The code below will allow the ball to roll in all directions using the WASD keys for up, left, back, and right movement:

function Script:Start()
--Create a camera
self.camera = Camera:Create()
--Update the camera
self:UpdateCamera()
end

--Adjust the camera orientation relative to the ball
function Script:UpdateCamera()
self.camera:SetRotation(45,0,0)
self.camera:SetPosition(self.entity:GetPosition())
self.camera:Move(0,0,-4)
end

function Script:UpdatePhysics()
--Get the game window
local window = Window:GetCurrent()
--Add force to the player when a key is pressed
if window:KeyDown(Key.W) then self.entity:AddForce(0,0,10,true) end
if window:KeyDown(Key.A) then self.entity:AddForce(-10,0,0,true) end
if window:KeyDown(Key.D) then self.entity:AddForce(10,0,0,true) end
if window:KeyDown(Key.S) then self.entity:AddForce(0,0,-10,true) end
end

function Script:UpdateWorld()
--Update the camera each frame
self:UpdateCamera()
end


Viola! You now have your very own moving ball.