GOingTunneling/gameobject.go

88 lines
2.5 KiB
Go

package main
import (
"github.com/veandco/go-sdl2/sdl"
"image/color"
)
type GameObject struct {
baseRect sdl.Rect
borderRect sdl.Rect
orientation uint8
visualRects [][]*ColoredRect
colors []color.Color
}
type ColoredRect struct {
color color.Color
rect *sdl.Rect
}
func adjustRectToCamera(object *sdl.Rect, camera *sdl.Rect) *sdl.Rect {
return &sdl.Rect{
X: object.X - camera.X,
Y: object.Y - camera.Y,
W: object.W,
H: object.H,
}
}
func (gameObject *GameObject) adjustRectToCamera(offset *sdl.Rect, camera *sdl.Rect) *sdl.Rect {
return &sdl.Rect{
X: gameObject.baseRect.X + offset.X - camera.X,
Y: gameObject.baseRect.Y + offset.Y - camera.Y,
W: offset.W,
H: offset.H,
}
}
func (gameObject *GameObject) render(camera *sdl.Rect, surface *sdl.Surface) {
if camera.HasIntersection(&gameObject.baseRect) {
if Debug {
gameObject.borderRect = sdl.Rect{
X: gameObject.baseRect.X - 1,
Y: gameObject.baseRect.Y - 1,
W: gameObject.baseRect.W + 2,
H: gameObject.baseRect.H + 2,
}
borderRectFinal := adjustRectToCamera(&gameObject.borderRect, camera)
baseRectFinal := adjustRectToCamera(&gameObject.baseRect, camera)
surface.FillRect(borderRectFinal, sdl.MapRGBA(surface.Format, 20, 192, 128, 64))
surface.FillRect(baseRectFinal, sdl.MapRGBA(surface.Format, 255, 20, 10, 64))
}
if RenderGameObjects {
for _, coloredRect := range gameObject.visualRects[gameObject.orientation] {
finalRect := gameObject.adjustRectToCamera(coloredRect.rect, camera)
r, g, b, a := coloredRect.color.RGBA()
surface.FillRect(finalRect, sdl.MapRGBA(surface.Format, uint8(r), uint8(g), uint8(b), uint8(a)))
}
}
}
}
func (gameObject *GameObject) addColoredRect(x, y, w, h int32, color uint8) {
if gameObject.visualRects == nil {
gameObject.visualRects = make([][]*ColoredRect, 0)
}
if uint8(len(gameObject.visualRects)) <= gameObject.orientation {
gameObject.visualRects = append(gameObject.visualRects, make([]*ColoredRect, 0))
}
if uint8(len(gameObject.colors)) > color {
gameObject.visualRects[gameObject.orientation] = append(gameObject.visualRects[gameObject.orientation],
&ColoredRect{
color: gameObject.colors[color],
rect: &sdl.Rect{
X: x, Y: y, W: w, H: h,
},
})
}
}
func (gameObject *GameObject) getCurrentRects() []*ColoredRect {
return gameObject.visualRects[gameObject.orientation]
}
func (gameObject *GameObject) addColor(color color.Color) {
gameObject.colors = append(gameObject.colors, color)
}