0 votes

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. :)

in Engine by (391 points)

1 Answer

0 votes

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

by (111 points)

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 )

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

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?

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.