【平凡晓声 Cocos2d-x】虚拟按键控制精灵移动1

    xiaoxiao2021-03-25  134

    虚拟按键控制精灵移动1

    最近想做过街机类的游戏,做这类游戏,首先我想到的就是精灵的移动,就是当按键按下时,精灵进行移动,当按键抬起时,精灵停止移动。 查阅了相关资料,最后整理出了两种方法分享给大家,废话不多说了,开干。

    1.通过touch点击事件和schedule计划任务控制精灵移动 1.1首先要给场景加个背景图:

    auto backGround = Sprite::create("background/bg1.jpg"); backGround->setPosition(visibleSize.width / 2, visibleSize.height / 2); backGround->setScale(visibleSize.width / backGround->getContentSize().width, visibleSize.height / backGround->getContentSize().height); this->addChild(backGround, 0);

    有的时候我们的图片可能和窗口大小不一样,所以我在setScanle的时候用了一个小技巧,为了能够让背景图片填充满窗口(不管图片大还是小)。 1.2加入我们要用到的精灵(这里我简单的绘制了一个帧动画)

    void HelloWorld::hero_Move() { Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); Vector<SpriteFrame*> allframe; for (int i = 1; i <= 8; i++) { auto spFrame = SpriteFrame::create(StringUtils::format("39669-%d.png", i), Rect(0, 0, 150, 150)); allframe.pushBack(spFrame); } auto animation = Animation::createWithSpriteFrames(allframe, 0.2f); auto animate = Animate::create(animation); auto sp = Sprite::create(); sp->setPosition(visibleSize.width / 2, visibleSize.height / 2); sp->setScale(0.5); sp->setTag(1); this->addChild(sp); sp->runAction(RepeatForever::create(animate));}

    这两步完成如图所示,接下来就是重头戏了 1.3添加点击事件 .h文件中

    virtual bool onTouchBegan(Touch *touch, Event *unused_event); virtual void onTouchMoved(Touch *touch, Event *unused_event); virtual void onTouchEnded(Touch *touch, Event *unused_event); //点击移动的计划任务 void toch_Move(float dt);

    .cpp文件中

    //处理点击交互事件 //添加监听 auto listener = EventListenerTouchOneByOne::create(); //绑定回调函数 listener->onTouchBegan = CC_CALLBACK_1(HelloWorld::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_1(HelloWorld::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_1(HelloWorld::onTouchEnded, this); //将回调函数添加到事件分发器中 Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); //点击鼠标事件 bool HelloWorld::onTouchBegan(Touch *touch, Event *unused_event) { Point touchLocation = touch->getLocationInView(); Point touchLocation2 = Director::getInstance()->convertToGL(touchLocation); //获取鼠标坐标点,并判断是否在一定的范围内,如果是,精灵移动 if (touchLocation2.x > 820 && touchLocation2.y < 100) { this->schedule(schedule_selector(HelloWorld::toch_Move), 0.2); } return true; } //移动鼠标 void HelloWorld::onTouchMoved(Touch *touch, Event *unused_event) { } //停止点击 void HelloWorld::onTouchEnded(Touch *touch, Event *unused_event) { //停止点击,取消计划任务 this->unschedule(schedule_selector(HelloWorld::toch_Move)); } //计划任务 void HelloWorld::toch_Move(float dt) { this->getChildByTag(1)->setPositionX(this->getChildByTag(1)->getPositionX() + 15); }

    如图:

    右下的按钮我只是加了一张图片,所以没有点击效果 要去开会了,今天就先到这,下次给大家分享如何用按钮来实现控制精灵移动,有点击效果哦。

    转载请注明出去,谢谢合作。

    转载请注明原文地址: https://ju.6miu.com/read-5925.html

    最新回复(0)