Created
June 14, 2018 12:17
-
-
Save egbulmer/fc5a0610585838425c8aa52df5830c63 to your computer and use it in GitHub Desktop.
Godot Rust: Working through “Dodge the Creeps!”
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // player.rs | |
| use gd; | |
| use gd::{ GodotString, Vector2 }; | |
| use gd::init::{ Property, PropertyHint, PropertyUsage }; | |
| const DEFAULT_SPEED: f64 = 400.0; | |
| godot_class! { | |
| class Player: gd::Area2D { | |
| fields { | |
| speed: f64, | |
| screen_size: gd::Vector2, | |
| } | |
| setup(builder) { | |
| builder.add_property( | |
| Property { | |
| name: "player/speed", | |
| default: DEFAULT_SPEED, | |
| hint: PropertyHint::None, | |
| getter: |this: &mut Player| this.speed, | |
| setter: |this: &mut Player, val| this.speed = val, | |
| usage: PropertyUsage::DEFAULT, | |
| } | |
| ); | |
| } | |
| constructor(header) { | |
| Player { | |
| header, | |
| speed: DEFAULT_SPEED, | |
| screen_size: Vector2::new(480.0, 720.0), | |
| } | |
| } | |
| export fn _ready(&mut self) { | |
| let parent = self.as_parent(); | |
| self.screen_size = parent.get_viewport() | |
| .expect("should have a viewport") | |
| .get_size(); | |
| } | |
| export fn _process(&mut self, delta: f64) { | |
| let mut vel = Vector2::new(0.0, 0.0); | |
| let input = gd::Input::godot_singleton(); | |
| if input.is_action_pressed(GodotString::from_str("ui_right")) { | |
| vel.x += 1.0; | |
| } | |
| if input.is_action_pressed(GodotString::from_str("ui_left")) { | |
| vel.x -= 1.0; | |
| } | |
| if input.is_action_pressed(GodotString::from_str("ui_down")) { | |
| vel.y += 1.0; | |
| } | |
| if input.is_action_pressed(GodotString::from_str("ui_up")) { | |
| vel.y -= 1.0; | |
| } | |
| if vel.length() > 0.0 { | |
| // TODO: How to make this shorter? | |
| let mut sprite = self | |
| .as_parent() | |
| .as_node_2d() | |
| .get_node(gd::NodePath::from_str("AnimatedSprite")) | |
| .expect("Should have an attached AnimatedSprite node!") | |
| .cast::<gd::AnimatedSprite>() | |
| .expect("Should be castable to AnimatedSprite!"); | |
| sprite.play(); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment