Cocos2d-js官方完整项目教程翻译:九、实现相关的游戏逻辑

来源:互联网 发布:淘宝客服子账号 编辑:程序博客网 时间:2024/05/16 17:52

一、简介

在本教程中我们将实现游戏逻辑更新平视显示器和一个简单的手势识别

不废话了,让我们开始教程

二、更新游戏HUD

更新主角移动的距离

首先我们要添加updateMeter方法到StatusLayer类中

 updateMeter:function (px) {        this.labelMeter.setString(parseInt(px / 10) + "M");    }

该方法labelmeter不断变化的价值。在这里,我们使用parseInt函数将结果转换一个整数的值

争论PX代表像素所以每10像素是一米

现在我们应该每一帧调用这个方法

开放animationlayer.js更新功能开始添加以下代码

// update meter        var statusLayer = this.getParent().getParent().getChildByTag(TagOfLayer.Status);        statusLayer.updateMeter(this.sprite.getPositionX() - g_runnerStartX);
更新硬币计数

收集的主角时,一枚硬币硬币应该更新指示符

首先,让我们添加一个addcoin statuslayer方法

addCoin:function (num) {        this.coins += num;        this.labelCoin.setString("Coins:" + this.coins);    },

当玩家的碰撞与硬币我们应该调用这个方法

现在是时候去实现它

开放playscene.jscolisioncoinbegin方法的末尾添加以下代码

var statusLayer = this.getChildByTag(TagOfLayer.Status);        statusLayer.addCoin(1);

每当玩家有硬币碰撞colisioncoinbegin方法会被调用我们硬币数将增加一个

保存所有文件Git尝试一下:

这里是截图


四、添加游戏的游戏逻辑

设计并实现了游戏的结束覆盖层

为了让事情变得简单我们只添加一个菜单项在我们的游戏结束层中心

当您单击“重新启动菜单游戏将再次重新启动

这样的设计是非常简单的让我们实现它

这里是gameoverlayer.js整个实现

var GameOverLayer = cc.LayerColor.extend({    // constructor    ctor:function () {        this._super();        this.init();    },    init:function () {        this._super(cc.c4b(0, 0, 0, 180));        var winSize = cc.director.getWinSize();        var centerPos = cc.p(winSize.width / 2, winSize.height / 2);        cc.MenuItemFont.setFontSize(30);        var menuItemRestart = cc.MenuItemSprite.create(            cc.Sprite.create(s_restart_n),            cc.Sprite.create(s_restart_s),            this.onRestart, this);        var menu = cc.Menu.create(menuItemRestart);        menu.setPosition(centerPos);        this.addChild(menu);    },    onRestart:function (sender) {        cc.director.resume();        cc.director.runScene(new PlayScene());    }});

在这里,我们使用了两个精灵命名s_restart_ns_restart_s创造我们的启动菜单项

所以我们应该将资源文件添加资源目录,定义资源的路径

开放resource.js添加以下代码

restart_n_png : "res/restart_n.png",    restart_s_png : "res/restart_s.png"//add the following two lines at the end of g_resources array.    res.restart_n_png,    res.restart_s_png

的初始化方法的代码是自解释。但你要注意回调onrestart方法

我们所谓的恢复功能的cc.director。这是为什么吗?因为我们叫暂停的方法当玩家死亡

Game over当主角碰到岩石的时候

现在让我们显示游戏当玩家撞击岩石

开放playscene添加以下代码collisionrockbegin方法结束

 collisionRockBegin:function (arbiter, space) {        cc.log("==game over");        cc.director.pause();        this.addChild(new GameOverLayer());    },
现在我们再次运行游戏截图如下


实现你自己的简单的手势识别

部分,我们设计非常简单recognizer风光

我们甩开我们的手指屏幕底部on the up the recognizerto发现

算法检测the刷卡手势是非常直接的。when the touch事件检测的开始我们的第一次

(in the touch阵列。when the touch移动事件觉察,我们添加at the end of the touch阵列

我们可以简单地比较the difference of Xtodetermine the of two相邻重击的方向。

这里代码片段to do the魔术师

function Point(x, y){    this.X = x;    this.Y = y;}// class definefunction SimpleRecognizer(){    this.points = [];    this.result = "";}// be called in onTouchBeganSimpleRecognizer.prototype.beginPoint = function(x, y) {    this.points = [];    this.result = "";    this.points.push(new Point(x, y));}// be called in onTouchMovedSimpleRecognizer.prototype.movePoint = function(x, y) {    this.points.push(new Point(x, y));    if (this.result == "not support") {        return;    }    var newRtn = "";    var len = this.points.length;    var dx = this.points[len - 1].X - this.points[len - 2].X;    var dy = this.points[len - 1].Y - this.points[len - 2].Y;    if (Math.abs(dx) > Math.abs(dy)) {        if (dx > 0) {            newRtn = "right";        } else {            newRtn = "left";        }    } else {        if (dy > 0) {            newRtn = "up";        } else {            newRtn = "down";        }    }    // first set result    if (this.result == "") {        this.result = newRtn;        return;    }    // if diretcory change, not support Recongnizer    if (this.result != newRtn) {        this.result = "not support";    }}// be called in onTouchEndedSimpleRecognizer.prototype.endPoint = function() {    if (this.points.length < 3) {        return "error";    }    return this.result;}SimpleRecognizer.prototype.getPoints = function() {    return this.points;}

手势检测,我们可以称simplerecognizer端点得到最后结果

目前支持四个简单类型:上,下,左、右。您可以扩展您自己的更复杂

五、触碰事件玩家的跳跃动画和逻辑

添加跳跃动画

为了跳动画的实现,我们应该准备好我们自己的比赛,艺术。在这里我们都是为你做的

你可以从概要部分复制并粘贴running.plistrunning.png文件放入res目录下载整个项目

游戏开始时,玩家将运行直到他无限与岩石碰撞。我们想让玩家向上

因此我们可以更长一点时间玩游戏

球员跳跳下我们需要发挥相应的动画

首先,让我们添加两个成员变量animationlayer动画的动作

jumpUpAction:null,jumpDownAction:null,
接下来让我们添加initAction方法

 initAction:function () {        // init runningAction        var animFrames = [];        // num equal to spriteSheet        for (var i = 0; i < 8; i++) {            var str = "runner" + i + ".png";            var frame = cc.spriteFrameCache.getSpriteFrame(str);            animFrames.push(frame);        }        var animation = cc.Animation.create(animFrames, 0.1);        this.runningAction = cc.RepeatForever.create(cc.Animate.create(animation));        this.runningAction.retain();        // init jumpUpAction        animFrames = [];        for (var i = 0; i < 4; i++) {            var str = "runnerJumpUp" + i + ".png";            var frame = cc.spriteFrameCache.getSpriteFrame(str);            animFrames.push(frame);        }        animation = cc.Animation.create(animFrames, 0.2);        this.jumpUpAction = cc.Animate.create(animation);        this.jumpUpAction.retain();        // init jumpDownAction        animFrames = [];        for (var i = 0; i < 2; i++) {            var str = "runnerJumpDown" + i + ".png";            var frame = cc.spriteFrameCache.getSpriteFrame(str);            animFrames.push(frame);        }        animation = cc.Animation.create(animFrames, 0.3);        this.jumpDownAction = cc.Animate.create(animation);        this.jumpDownAction.retain();    },

在这个函数中,我们已经初始化玩家的所有动画

最后让我们初始化代码runningaction我们以前在init函数的调用,而不是initaction方法

//init  actionsthis.initAction();//        // init runningAction//        var animFrames = [];//        for (var i = 0; i < 8; i++) {//            var str = "runner" + i + ".png";//            var frame = cc.spriteFrameCache.getSpriteFrame(str);//            animFrames.push(frame);//        }//        var animation = cc.Animation.create(animFrames, 0.1);//        this.runningAction = cc.RepeatForever.create(cc.Animate.create(animation));
触碰事件

现在是时候来处理触摸事件。首先,我们应该使animationlayer触碰

添加下面的代码片段init方法结束

cc.eventManager.addListener({            event: cc.EventListener.TOUCH_ONE_BY_ONE,            swallowTouches: true,            onTouchBegan: this.onTouchBegan,            onTouchMoved: this.onTouchMoved,            onTouchEnded: this.onTouchEnded        }, this)

这两行代码可以激活功能的触摸调度

现在让我们添加的回调,我们需要我们的触摸事件

onTouchBegan:function(touch, event) {        var pos = touch.getLocation();        event.getCurrentTarget().recognizer.beginPoint(pos.x, pos.y);        return true;    },    onTouchMoved:function(touch, event) {        var pos = touch.getLocation();        event.getCurrentTarget().recognizer.movePoint(pos.x, pos.y);    },    onTouchEnded:function(touch, event) {        var rtn = event.getCurrentTarget().recognizer.endPoint();        cc.log("rnt = " + rtn);        switch (rtn) {            case "up":                event.getCurrentTarget().jump();                break;            default:                break;        }    },

当你触摸屏的ontouchbegan方法会被调用。当你把你的手指移动它ontouchmoved方法

被称为。当你释放你的手指ontouchended方法会被调用

在这里,我们用简单的手势识别器来检测“刷卡的手势

五、包装他们

现在让我们将所有的包装起来

首先,animationlayer开始添加下列枚举

// define enum for runner statusif(typeof RunnerStat == "undefined") {    var RunnerStat = {};    RunnerStat.running = 0;    RunnerStat.jumpUp = 1;    RunnerStat.jumpDown = 2;};

我们使用这些枚举代表不同国家主角

然后,我们应该animationlayer添加两个成员变量

 recognizer:null, stat:RunnerStat.running,// init with running status
recognizer初始化初始化方法:尽头

this.recognizer = new SimpleRecognizer();
最后,我们来实现我们的跳跃方法

jump:function () {        cc.log("jump");        if (this.stat == RunnerStat.running) {            this.body.applyImpulse(cp.v(0, 250), cp.v(0, 0));            this.stat = RunnerStat.jumpUp;            this.sprite.stopAllActions();            this.sprite.runAction(this.jumpUpAction);        }    },
我们也应该把这些东西更新功能

//in the update method of AnimationLayer    // check and update runner stat        var vel = this.body.getVel();        if (this.stat == RunnerStat.jumpUp) {            if (vel.y < 0.1) {                this.stat = RunnerStat.jumpDown;                this.sprite.stopAllActions();                this.sprite.runAction(this.jumpDownAction);            }        } else if (this.stat == RunnerStat.jumpDown) {            if (vel.y == 0) {                this.stat = RunnerStat.running;                this.sprite.stopAllActions();                this.sprite.runAction(this.runningAction);            }        }
多说一句话,不要忘记清理的东西。我们应该释放操作时的animationlayer退出

onExit:function() {        this.runningAction.release();        this.jumpUpAction.release();        this.jumpDownAction.release();        this._super();    },
您可能还需要检查是否所有创建的JS文件加载cocos2d.js文件或没有

六、总结

祝贺你!你已经完成了一个史诗般的教程

让我们看看我们在完成本教程

首先,我们已经学会了如何更新游戏HUD元素

然后我们添加游戏逻辑

最后我们已经创建了一个简单的手势识别器来处理我们的英雄跳跃动作控制

你可以从这里http://cocos2d-x.org/docs/tutorial/framework/html5/parkour-game-with-javascript-v3.0/chapter9/res/Parkour.zip下载最终项目

七、接下来做什么

在下一个教程中,我们将完成整个项目


0 0
原创粉丝点击