~/3D Vector Rotation in Golang from Scratch

Nov 15, 2021


To rotate a 3D vector in Golang, multiply it by a rotation matrix about the chosen axis. Below is a concise implementation.

Define a vector structure:

1
2
3
type Vec3 struct {
    X, Y, Z float64
}

Function to rotate about the Z axis by angle theta radians:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import "math"

func RotateZ(v Vec3, theta float64) Vec3 {
    cosT := math.Cos(theta)
    sinT := math.Sin(theta)
    return Vec3{
        X: v.X*cosT - v.Y*sinT,
        Y: v.X*sinT + v.Y*cosT,
        Z: v.Z,
    }
}

For rotation about the X or Y axis, adjust the matrix accordingly as seen in rotation matrices:

X axis example:

1
2
3
4
5
6
7
8
9
func RotateX(v Vec3, theta float64) Vec3 {
    cosT := math.Cos(theta)
    sinT := math.Sin(theta)
    return Vec3{
        X: v.X,
        Y: v.Y*cosT - v.Z*sinT,
        Z: v.Y*sinT + v.Z*cosT,
    }
}

Y axis example:

1
2
3
4
5
6
7
8
9
func RotateY(v Vec3, theta float64) Vec3 {
    cosT := math.Cos(theta)
    sinT := math.Sin(theta)
    return Vec3{
        X: v.X*cosT + v.Z*sinT,
        Y: v.Y,
        Z: -v.X*sinT + v.Z*cosT,
    }
}

See more on rotation matrices and Euler angles for complex use cases. This approach enables clear 3D vector rotation in any direction in Golang.

Tags: [golang] [rotation] [vector]