1. Home
  2. /
  3. Cocos2dx
  4. /
  5. Cocos2d-x Keyboard Input Movement

Cocos2d-x Keyboard Input Movement - Cocos2dx Typing CST Test

Loading…

Cocos2d-x Keyboard Input Movement — Cocos2dx Code

Moves a sprite with arrow keys.

#include "KeyboardScene.h"
#include "cocos2d.h"

USING_NS_CC;

bool KeyboardScene::init() {
	if (!Scene::init()) return false;

	sprite = Sprite::create("hero.png");
	sprite->setPosition(Vec2(200, 200));
	addChild(sprite);

	auto listener = EventListenerKeyboard::create();
	listener->onKeyPressed = [&](EventKeyboard::KeyCode key, Event*) {
		if (key == EventKeyboard::KeyCode::KEY_RIGHT_ARROW) sprite->setPositionX(sprite->getPositionX() + 10);
		if (key == EventKeyboard::KeyCode::KEY_LEFT_ARROW) sprite->setPositionX(sprite->getPositionX() - 10);
	};
	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

	return true;
}

Cocos2dx Language Guide

Cocos2d-x is a cross-platform, open-source C++ game engine optimized for 2D games, offering high performance, a lightweight architecture, scene graph system, physics, animations, particle effects, and deployment to mobile, desktop, web, and consoles.

Primary Use Cases

  • ▸2D mobile games
  • ▸Casual/hypercasual games
  • ▸Educational games/apps
  • ▸Lightweight 2D engines for indie developers
  • ▸Cross-platform 2D desktop or mobile publishing

Notable Features

  • ▸High-performance C++ core
  • ▸Scene graph architecture
  • ▸Sprites + Actions + Transitions
  • ▸Box2D & Chipmunk physics
  • ▸Cross-platform deployment

Origin & Creator

Cocos2d-x originated from the Python-based Cocos2d project, created by Ricardo Quesada. It was later rewritten in C++ by Chukong Technologies and released in 2010 as a fast cross-platform engine for mobile.

Industrial Note

Cocos2d-x dominates the mobile 2D gaming industry in Asia, powering thousands of games in China, Japan, and Korea - especially hypercasual games, casino games, match-3 titles, and educational products requiring fast rendering.

More Cocos2dx Typing Exercises

Cocos2d-x Simple Counter GameCocos2d-x Basic Hello World SceneCocos2d-x Touch Move SpriteCocos2d-x Sprite Movement with ActionsCocos2d-x UI Button ExampleCocos2d-x Particle Effect ExampleCocos2d-x Background MusicCocos2d-x Sprite Animation ExampleCocos2d-x Scene Transition Fade

Practice Other Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypher