Vector2.x.normalized() not working

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

This is the code

extends KinematicBody2D

var motion = Vector2()
var knomot = Vector2()
const SPEED = 0
const UP = Vector2(0,-1)

func _physics_process(delta):
	var motion
	if controlling == true:
		motion.x = motion.x.normalized() * SPEED
	else:
		motion.x = knomot.x.normalized() * SPEED * 1.5
	move_and_slide(motion, UP)

But I get the message "Invalid Call. Nonexistent function ‘normalized’ in base ‘Nil’,
What do I do?

:bust_in_silhouette: Reply From: Elis

You can only normalize a whole vector, here you’re trying to normalize only the .x coordinate, which is impossible =)

:bust_in_silhouette: Reply From: kidscancode

First of all, you put var motion in _physics_process() so now you have a new local motion variable that has no value. Delete this line. You’ve already declared the motion variable as a class variable at the top.

Second, 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.

Finally, you’re never assigning any value other than (0, 0) to motion so your body is never going to move in the move_and_slide() call.

If you’re new to working with KinematicBody2D, I recommend reading the following:Using KinematicBody2D

Also, for understanding vectors, I highly recommend reading this:
Vector Math

Thanks! It is helpful.

TheAsker | 2019-02-25 03:24