0 votes

Hi there!

I'm trying to implement a system that knocks the player back when you fire a gun. I've been trying to use $Head.rotation_degrees, but that only outputs one axis. When I print it, it outputs something like (-0, 138.78, 0) instead of 3 numbers.

This is my current (messy) code:

var knockback = Vector3()
aim = $Head.rotation_degrees
print(aim)
knockback += aim.z - 175
knockback += aim.x - 175
knockback += aim.y - 175
print(knockback)
velocity.x += knockback.x
velocity.y += knockback.y
velocity.z += knockback.z

Is there some other way I could implement a knock back system or get rotation_degrees to work?

Edit: I was able to get it to work using:

var knockback = Vector3()
aim = $Head/Camera.get_camera_transform().basis
knockback += (aim.z)
knockback.normalized()
knockback = knockback * -10
velocity -= knockback

Thanks for your answers!

in Engine by (51 points)
edited by

2 Answers

+1 vote
Best answer

By the looks of your code, $Head must some sort of a Spatial (3D) object. In that case $Head.rotation_degrees returns a Vector3 object. So, a 3D vector. In fact, you're treating it as such when you reference the x, y, and z components of your aim variable.

Since aim, knockback, and velocity all appear to be Vector3 objects, you can perform much of the math directly on the vectors themselves rather than their individual components.

For instance, you can replace those last 3 lines with velocity += knockback

I'm not exactly sure what you're looking for, but maybe check out the Vector Math topic for a basic vector overview?

https://docs.godotengine.org/en/3.1/tutorials/math/vector_math.html

by (16,848 points)
selected by
0 votes

(-0, 138.78, 0) is three numbers. If you're trying to move the player backwards use global_transform.basis.xform(Vector3.BACK * knockback) in a method like move_and_slide(), knockback in this case would be a float.

by (3,251 points)
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.