0 votes

I am trying to implement a knockback feature, everything seems right, but an error message pops up for the third line of this code from Player.gd:

func knockback(var enemypos):
velocity.y = min_jump_velocity

if position.x > enemypos:
    velocity = 800
elif  position.x < enemypos:
    velocity = -800

Over in Enemy.gd I have:

func _on_Hitbox_body_entered(body):
if body.name == "Player":
    body.knockback(position.x)

Not really sure why I'm getting an invalid operand call here. Still fairly new to Godot and programming in general.

I tried using enemypos.x, but that presents an "Invalid get index 'x' (on base: 'float')" error.

Any help is appreciated! Thank you.
(haven't been able to mess around with this code to see how 800 works...lol)

Godot version Godot 3.2.3 Win64
in Engine by (12 points)

1 Answer

0 votes

This is only a guess, but is your velocity variable defined as a Vector2 (i.e. does it contain an x and y component)? If so, you are trying to set a vector of two values equal to a single number (float).

Perhaps try

if position.x > enemypos:
    velocity.x = 800
elif  position.x < enemypos:
    velocity.x = -800

(This will only provide horizontal knockback).

by (63 points)
edited by

velocity is defined as

var velocity = Vector2()

The full code can be viewed here via Pastebin

edit: the knockback is different as I was trying some various methods

Right, so that is the problem. velocity is a Vector2 but you are trying to make it a float by making it equal to 800. Did the code change work for you?

I got it to be error free with this in Player.gd:

func knockback(var enemypos):
velocity.y = min_jump_height

if position.x > enemypos.x:
    velocity.x = 2 * Globals.UNIT_SIZE
elif position.x < enemypos.x:
    velocity.x = 2 * Globals.UNIT_SIZE

on the Enemy.gd:

func _on_Hitbox_body_entered(body):
if body.name == "Player":
    body.knockback(position)

This seems to work for the x axis, but not the y axis, whereas before the y axis was working but not the x axis.

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 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 webmaster@godotengine.org with your username.