2018-01-11 07:52:23 -06:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"image"
|
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
_ "image/png"
|
|
|
|
|
|
|
|
"github.com/faiface/pixel"
|
|
|
|
"github.com/faiface/pixel/pixelgl"
|
|
|
|
)
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
windowWidth = 600
|
|
|
|
windowHeight = 450
|
|
|
|
foregroundHeight = 149
|
|
|
|
// This is the scrolling speed (pixels per second)
|
2018-01-12 05:19:58 -06:00
|
|
|
// Negative values will make background to scroll to the left,
|
|
|
|
// positive to the right.
|
|
|
|
backgroundSpeed = -60
|
|
|
|
foregroundSpeed = -120
|
2018-01-11 07:52:23 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
func run() {
|
|
|
|
cfg := pixelgl.WindowConfig{
|
2018-01-12 05:23:10 -06:00
|
|
|
Title: "Parallax scrolling demo",
|
2018-01-11 07:52:23 -06:00
|
|
|
Bounds: pixel.R(0, 0, windowWidth, windowHeight),
|
|
|
|
VSync: true,
|
|
|
|
}
|
|
|
|
win, err := pixelgl.NewWindow(cfg)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
2018-01-12 05:31:00 -06:00
|
|
|
// Pic must have double the width of the window, as it will scroll to the left or right
|
2018-01-11 07:52:23 -06:00
|
|
|
picBackground, err := loadPicture("background.png")
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
picForeground, err := loadPicture("foreground.png")
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
2018-01-12 05:19:58 -06:00
|
|
|
background := NewScrollingBackground(picBackground, windowWidth, windowHeight, backgroundSpeed)
|
|
|
|
foreground := NewScrollingBackground(picForeground, windowWidth, foregroundHeight, foregroundSpeed)
|
2018-01-11 07:52:23 -06:00
|
|
|
|
|
|
|
last := time.Now()
|
|
|
|
for !win.Closed() {
|
|
|
|
dt := time.Since(last).Seconds()
|
|
|
|
last = time.Now()
|
2018-01-12 05:19:58 -06:00
|
|
|
background.Update(win, dt)
|
|
|
|
foreground.Update(win, dt)
|
2018-01-11 07:52:23 -06:00
|
|
|
win.Update()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
pixelgl.Run(run)
|
|
|
|
}
|