ebiten cube move
video demo
idea
1. Define a block structure
2. Draw a square
3. Write the logic code for the block movement
1. Define a block structure
A square has a starting point (x, y) and width, height, because it needs to move, so the movement speed is indispensable
type Block struct {
x float64
y float64
width float64
height float64
speed float64
}
type Game struct {
block * Block
}
2. Draw a square
ebitenuitl
draw squares using the built-in function
func ( block * Block) BlockDraw ( screen * ebiten. Image) {
ebitenutil. DrawRect ( screen, block. x, block. y, block. width, block. height, color. NRGBA{
R: 0 , G: 255 , B: 0 , A: 255 } )
}
3. Block movement logic code
To move up, down, left, and right, when the arrow keys are pressed, the block can be moved by modifying the coordinates of the block
func ( block * Block) BlockUpdate ( ) {
if ebiten. IsKeyPressed ( ebiten. KeyLeft) {
block. x-= block. speed
} else if ebiten. IsKeyPressed ( ebiten. KeyRight) {
block. x+= block. speed
} else {
block. x+= 0
}
if ebiten. IsKeyPressed ( ebiten. KeyUp) {
block. y-= block. speed
} else if ebiten. IsKeyPressed ( ebiten. KeyDown) {
block. y+= block. speed
} else {
block. x+= 0
}
}
Initialize data (the data in the Game structure needs to be initialized before calling)
Initialize the defined data
func NewGame ( ) * Game{
return & Game{
& Block{
100 , 100 , 5 , 5 , 1 } ,
}
}
full code
type Block struct {
x float64
y float64
width float64
height float64
speed float64
}
type Game struct {
block * Block
}
func ( block * Block) BlockDraw ( screen * ebiten. Image) {
ebitenutil. DrawRect ( screen, block. x, block. y, block. width, block. height, color. NRGBA{
R: 0 , G: 255 , B: 0 , A: 255 } )
}
func ( block * Block) BlockUpdate ( ) {
if ebiten. IsKeyPressed ( ebiten. KeyLeft) {
block. x -= block. speed
} else if ebiten. IsKeyPressed ( ebiten. KeyRight) {
block. x += block. speed
} else {
block. x += 0
}
if ebiten. IsKeyPressed ( ebiten. KeyUp) {
block. y -= block. speed
} else if ebiten. IsKeyPressed ( ebiten. KeyDown) {
block. y += block. speed
} else {
block. x += 0
}
}
func ( g * Game) Update ( ) error {
g. block. BlockUpdate ( )
return nil
}
func ( g * Game) Draw ( screen * ebiten. Image) {
g. block. BlockDraw ( screen)
}
func ( g * Game) Layout ( outsideWidth, outsideHeight int ) ( screenWidth, screenHeight int ) {
return 480 , 320
}
func NewGame ( ) * Game {
return & Game{
& Block{
100 , 100 , 5 , 5 , 1 } ,
}
}
func main ( ) {
ebiten. SetWindowTitle ( "边界限制" )
ebiten. SetWindowSize ( 960 , 640 )
game := NewGame ( )
if err := ebiten. RunGame ( game) ; err != nil {
log. Fatal ( "启动失败:" , err)
}
}