Example #1
0
File: main.go Project: ryan-x/goop
func messages(w http.ResponseWriter, r *http.Request) {
	c, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer c.Close()
	// i := 5
	rect := Rect{ID: 1, X: 10, Y: 0, Height: 50, Width: 50}
	go func() {
		for {
			_, message, err := c.ReadMessage()
			if err != nil {
				log.Println("read:", err)
				break
			}
			log.Printf("recv: %s", message)
			msg := string(message)

			if msg == KeyRight {
				rect.XVector = physics.AddVectors(rect.XVector, physics.Vector(20))
			} else if msg == KeyLeft {
				rect.XVector = physics.AddVectors(rect.XVector, physics.Vector(-20.0))
			}

			if msg == KeyUp {
				rect.YVector = physics.AddVectors(rect.YVector, physics.Vector(20))
			} else if msg == KeyDown {
				rect.YVector = physics.AddVectors(rect.YVector, physics.Vector(-20))
			}

		}
	}()
	for {
		rect.Tick()
		if err := c.WriteJSON(rect); err != nil {
			log.Println("write:", err)
			break
		}
		rect.XVector = Friction(rect.XVector)
		rect.YVector = Friction(rect.YVector)
		// i += 5

		// if rect.X > 50 {
		// 	i = -5
		// } else if rect.X == 0 {
		// 	i = 5
		// }

		// rect.X += i
		// rect.Y += i
		// log.Println(rect)
		time.Sleep(15 * time.Millisecond)
		// time.Sleep(1 * time.Second)
	}
}
Example #2
0
File: main.go Project: ryan-x/goop
func Friction(v physics.Vector) physics.Vector {
	if v.Magnitude() < 1 {
		return physics.Vector(0.0)
	}

	if v.Direction() == physics.PositiveDirection {
		return physics.AddVectors(v, physics.Vector(-1.0))
	}
	return physics.AddVectors(v, physics.Vector(1.0))
}