|
|
|
 |
Attention |
Topic was automatically imported from the old Question2Answer platform. |
 |
Asked By |
ChaosX2020 |
(beginner)
This code works without normalized.
Like so [ velocity = velocity * speed]
So why is it necessary to use normalized ?
I tried to read about Vector math in documentation.
But because of its technical explanation. I couldn’t wrap my head around it.
Is there a way I can visually see in the game …what normalized is doing ?
I also read this explanation earlier but I couldn’t understand the meaning of
scaling …
normalizing is a function performed on vectors. It means taking a vector and scaling its length to 1. So for example the vector (1, 1) would become (0.707, 0.707). However, you can’t normalize only the x component.
var velocity = Vector2()
export (int) var speed = 400
func get_input():
velocity = Vector2()
if Input.is_action_pressed("ui_right"):
velocity.x += 1
if Input.is_action_pressed("ui_left"):
velocity.x -= 1
velocity = velocity.normalized() * speed
func _physics_process(delta):
get_input()
velocity = move_and_slide(velocity)
|
|
|
 |
Reply From: |
RedBlueCarrots |
A normalized vector, or unit vector, is a vector with a length of 1 unit. So by normalizing velocity and multiplying it by the speed, the length (or magnitude) of your velocity will be equal to your speed.
Without normalized, your player would steadily increase in speed without limit, whereas with normalized it will always be at the same speed with no acceleration
To clarify, normalization is not done automatically for performance reasons. If your vector is already normalized, normalizing it again will waste CPU cycles that could be spent elsewhere.
Calinou | 2020-05-19 13:31
Thanks. It finally clicked after I used the print statement to see what the code was doing. And like you said it gradually increases in speed without normalized.
ChaosX2020 | 2020-05-20 02:32
|
|
|
 |
Reply From: |
supper_raptor |
In your code
var velocity = Vector2()
export (int) var speed = 400
func get_input():
velocity = Vector2()
if Input.is_action_pressed("ui_right"):
velocity.x += 1
if Input.is_action_pressed("ui_left"):
velocity.x -= 1
velocity = velocity.normalized() * speed
func _physics_process(delta):
get_input()
velocity = move_and_slide(velocity)
if you don’t use normalized()
nothing will happen because your player only moves left
or right
but if your player moved up
and you pressed up
and left
at the same time , your player will move faster. your player would move 1.414
times faster in top -left direction.
It is because velocity
is(1,1)
and its magnitude is sqrt( 1*1 +1*1) = 1.414
While if you do normalized() velocity
is (0.707,0.707)
and its magnitude is sqrt( 0.707*0.707 + 0.707*0.707) = 1
we need to keep its magnitude to 1 so we use normalized()
Thanks. I finally understand how to use the code.
ChaosX2020 | 2020-05-20 02:34