Quantcast
Channel: Cocos Forums - Latest topics
Viewing all articles
Browse latest Browse all 17083

Keyboard Movement

$
0
0

@OMFGnikitpad wrote:

So I have this code to make the character move on keyboard input. It works pretty well, but after it moves, in order to move it again I have to press the keyboard button again which is annoying. I want to move continously on key hold without having to press the button again.

    auto eventListener = EventListenerKeyboard::create();
eventListener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event) {
	Vec2 loc = event->getCurrentTarget()->getPosition();
	int i;
	switch (keyCode) {
	case EventKeyboard::KeyCode::KEY_LEFT_ARROW:
	case EventKeyboard::KeyCode::KEY_A:
		//More lines to avoid bugs
		for (int i = 0; i < 5; ++i) {
			event->getCurrentTarget()->setPosition(--loc.x, loc.y);
		}
		break;
	case EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
	case EventKeyboard::KeyCode::KEY_D:
		for (int i = 0; i < 5; ++i) {
			event->getCurrentTarget()->setPosition(++loc.x, loc.y);
		}
		break;
	case EventKeyboard::KeyCode::KEY_UP_ARROW:
	case EventKeyboard::KeyCode::KEY_W:
		for (int i = 0; i < 5; ++i) {
			event->getCurrentTarget()->setPosition(loc.x, ++loc.y);
		}

		break;
	case EventKeyboard::KeyCode::KEY_DOWN_ARROW:
	case EventKeyboard::KeyCode::KEY_S:
		//Same here
		for (int i = 0; i < 5; ++i) {
			event->getCurrentTarget()->setPosition(loc.x, --loc.y);
		}
		break;
	}
	//End of move on key script
};

It works pretty well

Posts: 2

Participants: 2

Read full topic


Viewing all articles
Browse latest Browse all 17083

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>