How do you lerp only the x posistion

Godot Version

4.3

Question

`my code uses position but if i try position.x it doesnt work here is what i have
extends AnimatableBody2D
@onready var raycast = $RayCast2D
var MOVE_SPEED = 1

Called every frame. ‘delta’ is the elapsed time since the previous frame.

func _process(delta: float) → void:
var location = raycast.get_collision_point()
print(location)

if raycast.is_colliding():
	position.x = position.x.lerp(location, delta * MOVE_SPEED)
$AnimatedSprite2D.play("idle")

`

please use the </> button to format code. why does everyone have trouble doing it?

your code is invalid and should be throwing errors. read them and they will tell you what’s wrong.

what you can do to write better code is to define a type for your variables when you create them.

in this case location should be Vector2 because that’s what the function returns

var location : Vector2 = raycast.get_collision_point()

avoid using variables without a type.

the problem you have is exactly for that reason, lerp of position x should take a float, but you are passing a Vector2

position.x = position.x.lerp(location, delta * MOVE_SPEED)

you should maybe pass the X of location:

position.x = position.x.lerp(location.x, delta * MOVE_SPEED)

I guess you are getting an error because you are calling lerp on a float. It’s always helpful to post the errors you are getting (in addition to formatting your code as @jesusemora mentioned).

In any case, lerp is a functions on Vectors not floats. You could get ‘x’ from the interpolated vector and only then assign it to the position or simply implement ‘lerp’ yourself (or use the global function). See Interpolation — Godot Engine (stable) documentation in English.

Edit: Just if it’s not clear what I mean: Move the .x after the lerp. Vector2.lerp returns a vector.

Edit 2: I just saw that you also asked the question in another thread. Just leaving the other answer by @gertkeno here for anybody stumbling upon this: How do I tell my enemy script where the player is - #12 by gertkeno

1 Like

oh, that’s because you need to use the other lerp, the one in globalscope.
you are currently using a lerp that belongs to a vector2.

so it should look like this:
position.x = lerp(position.x, location.x, delta * MOVE_SPEED)

thank you tons ive been spending the last few hours on this problem