SFML community forums
Bindings - other languages => DotNet => Topic started by: chilliboy999 on September 11, 2013, 03:40:54 pm
-
Hey ho ;)
i've got a problem with pressing multiple keys at the same time. I want to move an object diagonal when
i press e.g. up and right. But my object only moves in one of these directions.
I also read some topics in this forum where people had the same problem, but the solutions didnt work.
Here's my code:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using SFML.Graphics;using SFML.Window;namespace Movement_SFML_2
._0
{ class Program
{ static RenderWindow rWin
; static Sprite sprite
; static void Main
(string[] args
) { rWin
= new RenderWindow
(new VideoMode
(500,
500),
"Movement"); rWin
.KeyPressed += new EventHandler
<KeyEventArgs
>(rWin_KeyPressed
); sprite
= new Sprite
(new Texture
("a.png")); rWin
.SetActive(); while (rWin
.IsOpen()) { rWin
.Clear(); rWin
.DispatchEvents(); rWin
.Draw(sprite
); rWin
.Display(); } } static void rWin_KeyPressed
(object sender, KeyEventArgs e
) { rWin
.SetTitle(e
.Code.ToString()); if (e
.Code == Keyboard
.Key.W) sprite
.Position = new Vector2f
(sprite
.Position.X, sprite
.Position.Y - 10); if (e
.Code == Keyboard
.Key.D) sprite
.Position = new Vector2f
(sprite
.Position.X + 10, sprite
.Position.Y); if (e
.Code == Keyboard
.Key.S) sprite
.Position = new Vector2f
(sprite
.Position.X, sprite
.Position.Y + 10); if (e
.Code == Keyboard
.Key.A) sprite
.Position = new Vector2f
(sprite
.Position.X - 10, sprite
.Position.Y); } }}
-
You need to separate your input handling from your updates/movement. The easiest way is to set a boolean flag when a key is pressed/released and then in your game loop do your movement depending on what is pressed. See my reply here (http://en.sfml-dev.org/forums/index.php?topic=12857.msg89999#msg89999) to see an example of how to do this.
By the way, you should really not be using global variables (static keyword) and instead use an OOP model. ;)
-
Thanks zsbzsb :D
It worked ;)