From 3720389fefd54de04ce400d25cfaa210671a08db Mon Sep 17 00:00:00 2001 From: mollusk Date: Tue, 16 Jan 2018 21:33:27 -0700 Subject: [PATCH] draw trees with left mouse click --- main.go | 49 +++++++++++++++++++++---------------------------- 1 file changed, 21 insertions(+), 28 deletions(-) diff --git a/main.go b/main.go index 83e9b3c..e8d7076 100644 --- a/main.go +++ b/main.go @@ -4,8 +4,8 @@ package main import ( "image" _ "image/png" + "math/rand" "os" - "time" "github.com/faiface/pixel" "github.com/faiface/pixel/pixelgl" @@ -45,42 +45,35 @@ func run() { panic(err) } - //smooth the edges of the image (antialiasing) - win.SetSmooth(true) - - //load a specific image and catch any errors - pic, err := loadPicture("hiking.png") + spritesheet, err := loadPicture("trees.png") if err != nil { panic(err) } - //create a sprite using the loaded image - sprite := pixel.NewSprite(pic, pic.Bounds()) + var treesFrames []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 { + treesFrames = append(treesFrames, pixel.R(x, y, x+32, y+32)) + } + } - //set the angle of the image - angle := 0.0 - - //set the time to compare later - last := time.Now() + var ( + trees []*pixel.Sprite + matrices []pixel.Matrix + ) //loop until window is closed by "X" button for !win.Closed() { - //compare the last time to delta time - dt := time.Since(last).Seconds() - last = time.Now() - - //set the angle according to delta time - angle += 3 * dt - + if win.JustPressed(pixelgl.MouseButtonLeft) { + tree := pixel.NewSprite(spritesheet, treesFrames[rand.Intn(len(treesFrames))]) + trees = append(trees, tree) + matrices = append(matrices, pixel.IM.Scaled(pixel.ZV, 4).Moved(win.MousePosition())) + } //refresh screen and set background color - win.Clear(colornames.Firebrick) - - //set the matrix and location of spirte in window - mat := pixel.IM - mat = mat.Rotated(pixel.ZV, angle) - mat = mat.Moved(win.Bounds().Center()) - sprite.Draw(win, mat) - + win.Clear(colornames.Forestgreen) + for i, tree := range trees { + tree.Draw(win, matrices[i]) + } //update the window win.Update() }