How do I keep my ball from rolling faster when rolling diagonally?

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

I have a ball rolling script, but the ball rolls faster if it is moving diagonally. I realize that I have to normalize the movement to fix it, but I am not sure how to do this in this case. here’s my code:

extends KinematicBody

var speed = 500
var rot_speed = 9
var acceleration = .2
var velocity = Vector3(0,0,0)

func _ready():
    pass

func _physics_process(delta):

#cam_target.rotation = Vector3(0,0,0)
if Input.is_action_pressed("ui_right") and Input.is_action_pressed("ui_left"):
	velocity.x = 0	 
elif Input.is_action_pressed("ui_right"):
	velocity.x = speed
	$MeshInstance.rotate_z(deg2rad(-rot_speed))
elif Input.is_action_pressed("ui_left"):
	velocity.x = -speed
	$MeshInstance.rotate_z(deg2rad(rot_speed))
else:
	velocity.x = lerp(velocity.x, 0, acceleration)

if Input.is_action_pressed("ui_up") and Input.is_action_pressed("ui_down"):
	velocity.z = 0
elif Input.is_action_pressed("ui_up"):
	velocity.z = -speed
	$MeshInstance.rotate_x(deg2rad(-rot_speed))
elif Input.is_action_pressed("ui_down"):
	velocity.z = speed
	$MeshInstance.rotate_x(deg2rad(rot_speed))
else:
	velocity.z = lerp(velocity.z, 0, acceleration)
move_and_slide(velocity * delta, Vector3(0,-1,0))

Thanks in advance. :slight_smile:

:bust_in_silhouette: Reply From: Maksanty

Before move_and_slide you must write velocity = velocity.normalized()

I tried it, but now the ball doesn’t move really at all. (it does move a tiny bit, but increasing the speed doesn’t do anything to help.) What should I do?

This is the code:

else:
	velocity.z = lerp(velocity.z, 0, acceleration)
velocity = velocity.normalized()
move_and_slide(velocity * delta, Vector3(0,-1,0))

(the else statement is just some of the code before )

Millard | 2019-11-20 16:05

velocity = velocity.normalized() * speed
move_and_slide(velocity * delta, Vector3(0,-1,0))

It was moving slowly because Vector3.normalized() returns a vector with a length of 1

Maksanty | 2019-11-20 16:07

Ok, I tried that, but now the ball won’t stop. I tried adding this code to fix it:

if velocity.length() > 0:
	velocity = velocity.normalized() * speed
else:
	velocity = velocity

but that didn’t seem to fix it either. Any idea what I should do?

Millard | 2019-11-20 18:46