ebiten小方块移动
视频演示
构思
1.定义一个方块的结构体 2.绘制一个方块 3.写出方块移动的逻辑代码
1.定义一个方块的结构体
一个方块具有起点(x,y)和宽度,高度,因为需要移动所以少不了移动速度
type Block struct {
x float64
y float64
width float64
height float64
speed float64
}
type Game struct {
block * Block
}
2.绘制一个方块
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的坐标实现方块移动
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
}
}
初始化数据(在Game结构体中的数据在调用前需要被初始化)
func NewGame ( ) * Game{
return & Game{
& Block{ 100 , 100 , 5 , 5 , 1 } ,
}
}
完整代码
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)
}
}