My question specifically pertains casting floats to integers. I tried using n = int(n)
as well as n = n as int
. Neither worked, silently doing nothing at all. Is there something I'm missing?
How do you cast a variable?
- Edited
Variable casting
Type casting is a key concept in typed languages. Casting is the conversion of a value from one type to another.
Imagine an Enemy in your game, that
extends Area2D
. You want it to collide with the Player, aKinematicBody2D
with a script calledPlayerController
attached to it. You use theon_body_entered
signal to detect the collision. With typed code, the body you detect is going to be a genericPhysicsBody2D
, and not yourPlayerController
on the_on_body_entered
callback.You can check if this
PhysicsBody2D
is your Player with theas
casting keyword, and using the colon:
again to force the variable to use this type. This forces the variable to stick to thePlayerController
type:func _on_body_entered(body: PhysicsBody2D) -> void: var player := body as PlayerController if not player: return player.damage()
As we’re dealing with a custom type, if the
body
doesn’t extendPlayerController
, theplayer
variable will be set tonull
. We can use this to check if the body is the player or not. We will also get full autocompletion on the player variable thanks to that cast.
I think in your examples you are forgetting to use the colon :
as per the above linked documentation:
@vijay_shastri said: I tried using
n = int(n)
as well asn = n as int
.
Make sure "n" is declared as int. If it's a float, then there will still be an implicit conversion. In your example you are assigning n to itself, which I don't believe will work (n will be implicitly converted to whatever it is). You should use two variables if they need to be different types.
Ah, yeah that sounds about right.