Orbit around Spatial and Move in and Out from it

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By sungen

Hello! I’m having some issues with my code. I’m new to Godot, and I’m trying to have my player character orbit around an enemy with A and D, as well as allow it to move in and out from it by using W and S. The orbiting works fine for the most part shy of some stuttering on start and stop, but I do not know how to have it move in and out from the enemy. I’ll attach the code and a picture below. I should note they are both Spatial for purposes not related to this.

var move_base = .05
    
var move_dist = (Input.get_action_strength("move_down") - Input.get_action_strength("move_up")) * move_base
var move_orb = (Input.get_action_strength("move_right") - Input.get_action_strength("move_left")) * move_base
    
# Rotation variables
# Subtract origin point from target's position
var pivot_radius = Vector3.ZERO - target.global_translation
    
var pivot_transform = Transform(transform.basis, target.global_translation)

# Rotate around target
transform = pivot_transform.rotated(Vector3(0, 1, 0), move_orb).translated(pivot_radius)

And as for the picture, the red (circle) is the orbiting path, and I’m trying to have the player be able to move along the green line intersecting it.
preview

What happens when you change move_base or pivot_radius, say, by increasing or decreasing their values?

spaceyjase | 2023-04-28 08:13

Can’t really modify pivot_radius, flags an error "Invalid operands ‘Vector3’ and ‘float’ in operator ‘-’.

sungen | 2023-04-28 09:01

:bust_in_silhouette: Reply From: sungen

Alright, I figured it out and I’ll attach my final results below. I ended up using a super simple way of rotating velocity around a point, being:

var move_base = 5 # Base speed of player
var velocity = Vector3(0, 0, 0) # Starting Vector3 point.

# I spent two days working on this only for it to be as easy as:
# Look at target every frame you update movement and rotate your final velocity around it. _ノ乙(、ン、)_

# Establish movement variables which will be used for strafing and distance RESPECTIVELY
var move_orbit = (Input.get_action_strength("move_right") - Input.get_action_strength("move_left")) * move_base
var move_dist = (Input.get_action_strength("move_down") - Input.get_action_strength("move_up")) * move_base

# Make current turn character look at target.
look_at(target.global_translation, Vector3(0, 1, 0))

# Modify velocity
velocity.x = move_orbit
velocity.z = move_dist

# Return velocity with modified angle to target.
return velocity.rotated(Vector3(0, 1, 0), get_rotation().y)

Which allowed me to get the finalized product being:
enter image description here