Home > Software design >  Math to rotate a point around an origin in Go
Math to rotate a point around an origin in Go

Time:05-30

Cannot remember the math to use from school however I want to rotate a point around an origin using Go/Golang.

Very basic idea below, x,y is the origin (center) and x2,y2 is the point on the circumference of the circle that moves. I want x2,y2 to rotate 360 around x,y continously.

x:= 10 // center x
y:= 10 // center y

x2 := 20 // rotating point x
y2 := 20 // rotating point y

xchange := ??? What math to use to calculate the change in x
ychange := ??? What math to use to calculate the change in y

Any help would be appreciated.

CodePudding user response:

You can parametrize a circular orbit around the point (x0, y0) with radius r as

x(t) = x0   r cos(t)
y(t) = y0   r sin(t)

You can work out r based on the two points you begin with. From there it’s just a matter of smoothly increasing t to simulate the progress of time.

CodePudding user response:

To rotate about an arbitrary center:

  • translate the designated center of rotation to (0,0)
  • rotate about the (0,0)
  • translate (0,0) back to the designated center.

Example code:

// translate center of rotation to (0,0)
dx := x_in - x_center
dy := y_in - y_center

// rotate about (0,0)
c := math.Cos(angle)
s := math.Sin(angle)
rotx := dx * c - dy * s
roty := dx * s   dy * c

// translate (0,0) back to center of rotation
x_out := rotx   x_center
y_out := roty   y_center
  • Related