github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/pixel/triangle/main.go (about) 1 package main 2 3 import ( 4 "image" 5 "image/color" 6 "math" 7 "time" 8 9 "github.com/faiface/pixel" 10 "github.com/faiface/pixel/pixelgl" 11 ) 12 13 func main() { 14 pixelgl.Run(run) 15 } 16 17 func run() { 18 cfg := pixelgl.WindowConfig{ 19 Title: "Draw a Triangle", 20 Bounds: pixel.R(0, 0, 480, 520), 21 Resizable: false, 22 VSync: true, 23 } 24 25 win, err := pixelgl.NewWindow(cfg) 26 if err != nil { 27 panic(err) 28 } 29 30 // create a test image 31 m := image.NewRGBA(image.Rect(0, 0, 100, 100)) 32 33 x, y := 0, 0 34 for i := 0; i < len(m.Pix); i += 4 { 35 if x >= 100 { 36 y++ 37 x = 0 38 } 39 x++ 40 41 m.Pix[i] = byte(y + x + (i * 1 % 32)) 42 m.Pix[i+1] = byte(y + (i * 2 % 32)) 43 m.Pix[i+2] = byte(y + (i * 3 % 32)) 44 m.Pix[i+3] = 0xFF 45 } 46 47 pd := pixel.PictureDataFromImage(m) 48 49 start := time.Now() 50 for !win.Closed() { 51 t := time.Since(start).Seconds() 52 53 win.SetClosed(win.JustPressed(pixelgl.KeyEscape)) 54 win.Clear(color.RGBA{0x80, 0x80, 0x80, 0xFF}) 55 56 sprite := pixel.NewSprite(pd, pd.Bounds()) 57 sprite.Draw(win, pixel.IM.Moved(win.Bounds().Center())) 58 59 s := math.Sin(t) 60 61 tridata := pixel.MakeTrianglesData(3) 62 tris := *tridata 63 tris[0].Picture = pixel.Vec{0.5, 0}.Scaled(100) 64 tris[1].Picture = pixel.Vec{0, s}.Scaled(100) 65 tris[2].Picture = pixel.Vec{1, 1}.Scaled(100) 66 67 tris[0].Intensity = 1 68 tris[1].Intensity = 1 69 tris[2].Intensity = 1 70 71 tris[0].Position = pixel.Vec{0.5, 0}.Scaled(100) 72 tris[1].Position = pixel.Vec{0, 1}.Scaled(100) 73 tris[2].Position = pixel.Vec{1, 1}.Scaled(100) 74 75 // using pixel.Drawer 76 drawer := pixel.Drawer{} 77 drawer.Triangles = tridata 78 drawer.Picture = pd 79 drawer.Draw(win) 80 81 // using pixel.Batch 82 // batch := pixel.NewBatch(tridata, pd) 83 // batch.Draw(win) 84 85 win.Update() 86 } 87 }