project-rpg/main.go

132 lines
2.5 KiB
Go

package main
import (
"fmt"
"image"
"math"
"os"
"time"
_ "image/png"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
"golang.org/x/image/colornames"
)
func loadPicture(path string) (pixel.Picture, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
return nil, err
}
return pixel.PictureDataFromImage(img), nil
}
func run() {
cfg := pixelgl.WindowConfig{
Title: "Pixel Rocks!",
Bounds: pixel.R(0, 0, 1024, 768),
VSync: true,
}
win, err := pixelgl.NewWindow(cfg)
if err != nil {
panic(err)
}
spritesheet, err := loadPicture("sprites.png")
if err != nil {
panic(err)
}
background, err := loadPicture("background.png")
if err != nil {
panic(err)
}
//batch := pixel.NewBatch(&pixel.TrianglesData{}, spritesheet)
var spritesFrames []pixel.Rect
for x := spritesheet.Bounds().Min.X; x < spritesheet.Bounds().Max.X; x += 32 {
for y := spritesheet.Bounds().Min.Y; y < spritesheet.Bounds().Max.Y; y += 32 {
spritesFrames = append(spritesFrames, pixel.R(x, y, x+79, y+92))
}
}
var (
camPos = pixel.ZV
camSpeed = 500.0
camZoom = 0.3
camZoomSpeed = 1.2
)
var (
frames = 0
second = time.Tick(time.Second)
)
playerX := win.Bounds().Max.X / 2
playerY := win.Bounds().Max.Y / 2
var (
playerXY = pixel.Vec{
playerX,
playerY,
}
)
last := time.Now()
for !win.Closed() {
dt := time.Since(last).Seconds()
last = time.Now()
playerXY = pixel.Vec{
playerX,
playerY,
}
cam := pixel.IM.Scaled(camPos, camZoom).Moved(win.Bounds().Center().Sub(camPos))
win.SetMatrix(cam)
bg := pixel.NewSprite(background, background.Bounds())
Sprite := pixel.NewSprite(spritesheet, spritesFrames[3])
//mouse := cam.Unproject(win.MousePosition())
win.Clear(colornames.Forestgreen)
bg.Draw(win, pixel.IM.Moved(win.Bounds().Center()))
Sprite.Draw(win, pixel.IM.Scaled(pixel.ZV, 4).Moved(playerXY))
if win.Pressed(pixelgl.KeyA) {
playerX -= camSpeed * dt
}
camPos.X = playerX
camPos.Y = playerY
if win.Pressed(pixelgl.KeyD) {
playerX += camSpeed * dt
}
if win.Pressed(pixelgl.KeyS) {
playerY -= camSpeed * dt
}
if win.Pressed(pixelgl.KeyW) {
playerY += camSpeed * dt
}
camZoom *= math.Pow(camZoomSpeed, win.MouseScroll().Y)
//batch.Draw(win)
win.Update()
frames++
select {
case <-second:
win.SetTitle(fmt.Sprintf("%s | FPS: %d", cfg.Title, frames))
frames = 0
default:
}
}
}
func main() {
pixelgl.Run(run)
}