Implementing a simple character using classes.
The example below shows how to implement a simple top down character using classes. I think it is pretty easy to understand and someone might be able to use it to step into object oriented programming (oop). I hope this is helpful. Cheers!
// This creates the class and tells the class what properties to use when created. In your main file's init() method use the 'new'
// keyword to create a class. This would look like 'myNewPlayer = new Player(0, 0, 2, "player", 32, 32). The values are going to depend
// on your game. The image parameter is the name of your sprite you made in the sprite editor.
Player = class
constructor = function(x, y, speed, image, width, height)
this.x = x
this.y = y
this.speed = speed
this.image = image
this.width = width
this.height = height
end
// Call this in your main file's update() method example: player.move()
move = function()
if keyboard.UP then
this.y += this.speed
end
if keyboard.DOWN then
this.y -= this.speed
end
if keyboard.RIGHT then
this.x += this.speed
end
if keyboard.LEFT then
this.x -= this.speed
end
// Comes from the 'helper' source file's Clamp Function. This file is linked from the main tutorial page.
this.x = clamp(this.x, -screen.width/2 + this.width/2, screen.width/2 - this.width/2)
this.y = clamp(this.y, -screen.height/2 + this.height/2, screen.height/2 - this.height/2)
end
// Put a call to this in your main file's draw() method such as 'player.draw()'
draw = function()
screen.drawSprite(this.image, this.x, this.y, this.width, this.height)
end
end