Apply gravity at a rotating object

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

What would be the best way to achieve this effect

I tried using kinematicBody2d but I’m struggling to switch the angle of the gravity while rotating

      extends KinematicBody2D
var RotateSpeed = 4
var Radius = Vector2.ONE*174
var MinRadius = 45
var _distanceToPivot
var _center = Vector2(180,320)
const GRAVITY = -200.0
var _angle = 0
var velocity = Vector2()
var gravityDir
var floorNormal = Vector2()

func _ready():
func _physics_process(delta): 
	_distanceToPivot = _center-self.position
	gravityDir = _distanceToPivot*GRAVITY
	_angle += 2*PI*delta / float(RotateSpeed)
	_angle = wrapf(_angle,-PI,PI)
	var pos = Vector2()
	pos.x = _center.x+cos(_angle)*Radius.x
	pos.y = _center.y+sin(_angle)*Radius.y
	velocity.y += GRAVITY * delta
	var motion = velocity * delta
	#velocity.x += gravityDir.x *delta
	#self.position = pos
	motion = move_and_slide(motion, _distanceToPivot.normalized())

Can’t figure out a matter of question.

sash-rc | 2021-08-22 10:55

I would keep gravity as a force (note that the code about to be shown may not work for your circumstances). You can use the .rotated function to rotate a velocity (at least, from my understanding).

var gravity_speed = 100
var rot_dir = 42

var velocity = Vector2()

func _physics_process(delta):
    velocity = Vector2(gravity_speed, 0).rotated(rot_dir)

Also note that the above code is not tested, sorry if it doesn’t work.

The code was inspired by code from the Tanks project from Kidscancode (thanks a lot).
For further reading: Topdown Tank Battle: Part 1 · KCC Blog

TheJokingJack | 2021-08-22 15:49

why do you even need an angle?
you have a center of gravity, the force is proportional to object.position-center_of_gravity.position, the direction is embedded in this vector

Andrea | 2021-08-24 17:54