上学笔记,二〇一五上学笔记

Pepsi-ColaBuilder 学习笔记二,spritebuilder

Chapter 3  Controlling and Scrolling

@implementation GameScene {
    __weak CCNode *_levelNode;
    __weak CCPhysicsNode *_physicalNode;
    __weak CCNode *_playerNode;
    __weak CCNode *_backgroundNode;
}

注意__weak关键字。总的来讲,声惠氏个obejct pointer
变量实际不是由类created
只怕说owned的时候,最佳都选择__weak,尤其是在cocos2d中,应该总是宣称二个援用,当那个援用不是parent或许node的“兄弟”(sibling)时。若无__weak关键字,暗中认可生成三个strong援引。

通过名字找到Player Node

在GameScene中增加代码:

- (void)didLoadFromCCB {
    NSLog(@"GameScene created!");
    // 使得可以接受输入的事件 (enable receiving input events)
    // 这句话允许GameScene类去接受触摸事件
    self.userInteractionEnabled = YES;
    // load the current level 载入当前level
    [self loadLevelNamed:nil];
}

- (void)loadLevelNamed:(NSString*)levelCCB {
    // 在scene中获取当前level的player,递归寻找
    _playerNode = [self getChildByName:@"player" recursively:YES];
    // 如果没有找到,NSAssert会抛出一个异常
    NSAssert1(_playerNode, @"player node not found in level:%@", levelCCB);
}

下边包车型大巴代码用于落到实处通过触摸移动物体到入手的位置

- (void)touchBegan:(CCTouch*)touch withEvent:(UIEvent*)event {
    _playerNode.position = [touch locationInNode:self];
}

NOTE:书中首先个参数类型为UITouch* 报错,改为CCTouch后就能够实现效果与利益。

查阅API,摘抄如下:

上学笔记,贰零壹伍学习笔记

参考:

http://www.cnblogs.com/TomXu/archive/2011/11/21/2257154.html

http://knockoutjs.com/documentation/introduction.html

touchBegan:withEvent:

Called when a touch began. Behavior notes:

- (void)touchBegan:(CCTouch *)touch withEvent:(CCTouchEvent *)event

复习:AngularJS的数目绑定

  • 显示文本

<p>{{greeting}}</p>
<!-- 或者 -->
<p ng-bind=”greeting”></p>
  • 表单输入

<form ng-controller=”SomeController”>
    <input type=”checkbox” ng-model=”youCheckedIt”>
</form>
  • 列表

<ul ng-controller=’StudentController’>
    <li ng-repeat=’student in students’>
        <a href=’/student/view/{{student.id}}’>{{student.name}}</a>
    </li>
</ul>
  •  表格

<table ng-controller=’AlbumController’>
    <tr ng-repeat=’track in album’>
        <td>{{$index+1}}</td>
        <td>{{track.name}}</td>
        <td>{{track.duration}}</td>
    </tr>
</table>

 使用$watch监察和控制数据模型的生成

Parameters

touch
Contains the touch.

event
Current event information.

Knockout基础学习

亲自过问代码出现错误,展现jquery-tmpl版本太久,参照他事他说加以考察消除办法。jquery.tmpl.js的下载地址:

https://raw.githubusercontent.com/BorisMoore/jquery-tmpl/master/jquery.tmpl.js

https://github.com/BorisMoore/jquery-tmpl

库的在线引用地址:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="./jquery.tmpl.js"></script>
<script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-latest.js"></script>

Discussion

  • If a touch is dragged inside a node which does not claim user
    interaction, a touchBegan event will be generated.
  • If node has exclusive touch, all other ongoing touches will be
    cancelled.
  • If a node wants to handle any touch event, the touchBegan method
    must be overridden in the node subclass. Overriding just touchMoved
    or touchEnded does not suffice.
  • To pass the touch further down the Cocos2D responder chain, call the
    super implementation, ie [super touchBegan:withEvent:].

入门

重要概念:

  • 申明式绑定
  • UI分界面自动刷新
  • 依傍追踪
  • 模板

启用绑定

ko.applyBindings(viewModel)

 数据模型

var viewModel = {
  chosenMeal: ko.observable(availableMeals[0])
}

数据

var availableMeals = [
    { mealName: 'Standard', description: 'Dry crusts of bread', extraCost: 0 },
    { mealName: 'Premium', description: 'Fresh bread with cheese', extraCost: 9.95 },
    { mealName: 'Deluxe', description: 'Caviar and vintage Dr Pepper', extraCost: 18.50 }
  ];

采纳绑定,写变量

Chosen meal: <select data-bind="options: availableMeals,
                              optionsText: 'mealName',
                              value: chosenMeal"></select>

行使绑定,读变量,并作为参数提须求函数

<p>
  You've chosen:
  <b data-bind="text: chosenMeal().description"></b>
  (price: )
</p>
<script>
  function formatPrice(price) {
    return price == 0 ? "Free" : "$" + price.toFixed(2);
  }        
</script>

See Also

  • CCTouch, CCTouchEvent

 Observables 可观看变量

概念

observables, Dependent Observables, Observable Array

主导成效

         observables 可观看变量 Dependency tracking 依赖追踪

         declarative bindings 显式绑定

         templating 模板

View-Model 视图模型

激活Knockout

ko.applyBindings(myViewModel, document.getElementById('someElementId'))

 可观望变量,注脚

var myViewModel = {
    personName: ko.observable('Bob'),
    personAge: ko.observable(123)
};

 可观看变量,读写

         读:myViewModel.personAge()

         写:myViewModel.personName(‘Mary’),辅助链式语法

         绑定,data-bind,注册到可观看变量

可观望变量,显示订阅

var subscription = myViewModel.personName.subscribe(function (newValue) { /* do stuff */ });
// ...then later...
subscription.dispose(); // I no longer want notifications

 重视可观望变量

var viewModel = {
       firstName: ko.observable('Bob'),
       lastName: ko.observable('Smith')
};
viewModel.fullName = ko.dependentObservable(function () {
    return this.firstName() + " " + this.lastName();
}, viewModel);

 从依赖变量写入可观望变量

viewModel.fullName = ko.dependentObservable({

    read: function () {
        return this.firstName() + " " + this.lastName();
    },

    write: function (value) {
        var lastSpacePos = value.lastIndexOf(" ");
        if (lastSpacePos > 0) { // Ignore values with no space character
            this.firstName(value.substring(0, lastSpacePos)); // Update "firstName"
            this.lastName(value.substring(lastSpacePos + 1)); // Update "lastName"
        }
    },
    owner: viewModel
});

 使用依赖变量数组observable array

var myObservableArray = ko.observableArray();    // Initially an empty array
myObservableArray.push('Some value');          // Adds the value and notifies observers

// This observable array initially contains three objects
var anotherObservableArray = ko.observableArray([
    { name: "Bungle", type: "Bear" },
    { name: "George", type: "Hippo" },
    { name: "Zippy", type: "Unknown" }
]);

 js等价读取音讯:length, indexOf, slice

js数组等价操作:pop, push, shift, unshift, reverse, sort, splice

非同一般操作:remove, removeAll

Declared In

CCResponder.h

 

分配Level-Node变量

在SpriteBuilder中分配变量和经过名字获取一个node是一致的,仅仅是个人习于旧贯难点。然而不引入频仍利用getChildByName:方法在schedule
methond中(不太懂那是什么点子)和updata:方法中,特别是递归查找和a
deep-node hierarch。

Caution:在Coca ColaBuilder中分红八个变量仅仅适用于CCB文件的直白descendants(后代–不知怎么样翻译),无法对经过Sub
File(CCBFile)导入的另二个CCB钦命node为变量或许properties。那也是怎么player
node通过名字获取。

打开GameScene.ccb,

图片 1

 

note:A doc root var assigns a node to a correspondingly named ivar or
property declared in the CCB root node’s custom class

Doc root
var:分配多少个node,为在CCB根node的自定义类中扬言的对峙应名字的变量只怕性质。

做完这步后,_levelNode变量会在它发送didLoadFromCCB新闻在此以前被CCB里德r分配,那是成立一个在CCB中包含的node的最简便易行,最管用的法子。

 

用CCActionMoveTo移动Player

为了平滑的移位player到钦赐地点,能够修改如下代码:

- (void)touchBegan:(CCTouch*)touch withEvent:(UIEvent*)event {
   // _playerNode.position = [touch locationInNode:self];
    CGPoint pos = [touch locationInNode:_levelNode];
    CCAction *move = [CCActionMoveTo actionWithDuration:0.2 position:pos];
    [_playerNode runAction:move];
}

触摸点根据_levelNode转化。那一点很关键,有限支撑了player能够在全数_levelNode上活动,并非被监管在荧屏空间中。可是那点近些日子还看不出来,因为还尚未拉长滚动(scrolling)。

然则此时,假设扩充duration(持续时间),会意识移动的动作并未增大,player也不会停在您最后一回点击的地点。所以必须加多多少个tag,有了那些tag,能够在施行新的动作之前,结束当前动作,代码改造如下:

- (void)touchBegan:(CCTouch*)touch withEvent:(UIEvent*)event {
   // _playerNode.position = [touch locationInNode:self];
    [_playerNode stopActionByTag:1];
    CGPoint pos = [touch locationInNode:_levelNode];
    CCAction *move = [CCActionMoveTo actionWithDuration:20.2 position:pos];
    move.tag = 1;
    [_playerNode runAction:move];
}

 

滚动Level(Scrolling the Level)

在2D嬉戏中,更常见的做法是倒转方向移动content layer,已完结滚动作效果应。

在Cocos2D和OpenGl中,未有camera的概念,唯有device screen(设备显示屏).

 

 Scheduling Updates(调治更新)

即便player移动到左边手和上边,那我们要做的事务莫过于是移动_levelNode向左侧和底下方向移动。player的岗位限定在level
node中,左下角右侧为(0,0),在这么些顺序中,范围是五千*500 points。

在GameScene中加多如下代码:

// the updata:method is automatically called once per frame
// update方法在每一帧都被自动调用
- (void)update:(CCTime)delta {
    // update scroll node position to player node, with offset to center player in the view
    [self scrollToTarget:_playerNode];
}

update:方法自动被Cocos2d调用,在底层,每一帧,node出现在显示屏此前,都回被调用。

不像从前的Cocos2d本子,你不再须求去明显调治更新(you no longer have to
explicitly schedule the update:method.)

您可以利用node schedule和unschedule方法调治别的的章程或blocks.(you can
still schedule other methods or blocks using the node schedule and
unschedule methods)

诸如:延迟运营一个selector,能够写为:

[self scheduleOnce:@selector(theDelayedMethod:)delay:2.5]:

下一场再一样的类中实现对应的selector。这一个selector必须运用一个CCTime参数:

-(void)theDelayedMethod:(CCTime)delta {

//your code

}

Caution:永世不要选用NSTimer等。这几个日子方法在node也许Cocos2d暂停时候不会自动制动踏板。

delta参数是delta time,或者difference in time。

在60帧每秒时,delta时间时临时取大致0.0167,单位是秒。

delta
time平常作为以同样的快慢移动nodes,而忽视帧速率。大家在那本书中不采取delta
time,因为大家采纳Cocos2d的情理引擎。

 

Moving the level Node in the Opposite Derection

向相反方向移动Level Node

在GameScene.m中增多scrollToTarget方法以完毕滚动:

- (void)scrollToTarget:(CCNode*)target {
    CGSize viewSize = [CCDirector sharedDirector].viewSize;
    CGPoint viewCenter = CGPointMake(viewSize.width / 2.0,viewSize.height / 2.0);
    CGPoint viewPos = ccpSub(target.positionInPoints, viewCenter);
    CGSize levelSize = _levelNode.contentSizeInPoints;
    viewPos.x = MAX(0.0, MIN(viewPos.x, levelSize.width - viewSize.width));
    viewPos.y = MAX(0.0,MIN(viewPos.y, levelSize.height - viewSize.height));
    _levelNode.positionInPoints = ccpNeg(viewPos);
}

前两行的机能是钦点view的尺码到viewSize,值为显示屏以points为单位的值。

然后计算view的宗旨点。

viewPos变量被开始化为目的的positionInPoints减去大旨点viewCenter。

其一应用ccpSub做的减法是为了保全指标node保持宗旨地方,假使不做这一步,指标node会消失在显示屏的左下角。

levelSize变量被定义为_lovelNode.contentSizeInPoints,在上面两行中,它用于夹住viewPos。

因为显示屏长久不应有比viewCenter滚动的更临近于level的边界,所以采取减法。每一个边界的离开相加等于viewSize。可能换句话说,能够滚动的区域是viewCenter的两倍可能三个viewSize
  ???

图片 2

level区域和可滚动区域的涉及图:箭头表示可滚动区域。注意player在近似level边界的时候曾经不在中央地点了。

d未完待续d 

 

http://www.bkjia.com/IOSjc/950690.htmlwww.bkjia.comtruehttp://www.bkjia.com/IOSjc/950690.htmlTechArticleSpriteBuilder 学习笔记二,spritebuilder Chapter 3
Controlling and Scrolling @implementation GameScene { __weak CCNode *
_levelNode; __weak CCPhysicsNode * _physicalNode; __we…

绑定语法一

         visible: 绑定到DOM成分,调整作而成分是不是出示

         text: 调控作而成分的文本值

         html: 调整作而成分呈现的HTML值

         css: 增加或删除三个或多少个CSS class到DOM成分上

         style: 增加或删除三个或多个DOM成分上的style值

         attr: 提供了一种办法得以安装DOM元素的其余属性值

绑定语法二

         click

         event, 例如keypress, mouseover, mouseout

         submit

         enable

         disable

绑定语法三

         value, <input>, <select>, <textarea>

         checked, <input type=’checkbox’>, <input
type=’radio’>

         options, <select>, <select size=’6’>

         selectedOptions, multi-select

         uniqueName

模板绑定

行使jquery.tmpl,你能够行使另外你模板引擎援助的语法。jquery.tmpl推行如下语法:

    ${ someValue } — 参谋文书档案

    {{html someValue}} — 参照他事他说加以考察文书档案

    {{if someCondition}} — 参照他事他说加以考察文书档案

    {{else someCondition}} — 参照他事他说加以考察文书档案

  {{each someArray}} — 参谋文书档案

创办自定义绑定

ko.bindingHandlers.yourBindingName = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
        // This will be called when the binding is first applied to an element
        // Set up any initial state, event handlers, etc. here
    },

    update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
        // This will be called once when the binding is first applied to an element,
        // and again whenever the associated observable changes value.
        // Update the DOM element based on the supplied values here.
    }
};

加载或保存JSON数据

加载或保存数据:举个例子使用jQuery的$.getJSON, $.post, $.ajax

转载ViewModel数据到JSON格式,偶然需求json2.js类库

         ko.toJS 转化为JS对象

         ko.toJSON 转化为JSON字符串

使用JSON更新ViewModel数据

  手动方式

// 载入冰解析JSON
var someJSON = /* 使用你期望的任何方法获取JSON */
var parsed = JSON.parse(someJSON);

// 更新view model属性
viewModel.firstName(parsed.firstName);
viewModel.pets(parsed.pets);

 恐怕利用 knockout.mapping

 使用Mapping插件

var viewModel = ko.mapping.fromJS(data); //创建ViewModel
ko.mapping.fromJS(data, viewModel); //更新ViewModel

用法:

         key, create, update, ignore, include, copy

三种方法开创viewModel

var viewModel = {
    firstName: ko.observable("Planet"),
    lastName: ko.observable("Earth")
};

viewModel.fullName = ko.dependentObservable({

    read: function() {
        return this.firstName() + " " + this.lastName();
    },

    write: function(value) {
        var lastSpacePos = value.lastIndexOf(" ");
        if (lastSpacePos > 0) { // Ignore values with no space character
            this.firstName(value.substring(0, lastSpacePos)); // Update "firstName"
            this.lastName(value.substring(lastSpacePos + 1)); // Update "lastName"
        }
    },
    owner: viewModel
});

 

var clickCounterViewModel = function() {
    this.numberOfClicks = ko.observable(0);

    this.registerClick = function() {
        this.numberOfClicks(this.numberOfClicks() + 1);
    }

    this.hasClickedTooManyTimes = ko.dependentObservable(function() {
        return this.numberOfClicks() >= 3;
    }, this);
};

ko.applyBindings(new clickCounterViewModel());

 

 应用比如

 

 常用的控件

图片 3

 源代码:视图

<div class="readout">
    <h3>What's in the model?</h3>
    <table>
        <tr>
            <td class="label">Text value:</td>
            <td data-bind="text: stringValue"></td>
        </tr>
        <tr>
            <td class="label">Password:</td>
            <td data-bind="text: passwordValue"></td>
        </tr>
        <tr>
            <td class="label">Bool value:</td>
            <td data-bind='text: booleanValue() ? "True" : "False"'></td>
        </tr>
        <tr>
            <td class="label">Selected option:</td>
            <td data-bind="text: selectedOptionValue"></td>
        </tr>
        <tr>
            <td class="label">Multi-selected options:</td>
            <td data-bind="text: multipleSelectedOptionValues"></td>
        </tr>
        <tr>
            <td class="label">Radio button selection:</td>
            <td data-bind="text: radioSelectedOptionValue"></td>
        </tr>
    </table>
</div>

<h3>HTML controls</h3>
<table>
    <tr>
        <td class="label">Text value (updates on change):</td>
        <td><input data-bind="value: stringValue" /></td>
    </tr>
    <tr>
        <td class="label">Text value (updates on keystroke):</td>
        <td><input data-bind='value: stringValue, valueUpdate: "afterkeydown"' /></td>
    </tr>
    <tr>
        <td class="label">Text value (multi-line):</td>
        <td><textarea data-bind="value: stringValue"> </textarea></td>
    </tr>
    <tr>
        <td class="label">Password:</td>
        <td><input type="password" data-bind="value: passwordValue" /></td>
    </tr>
    <tr>
        <td class="label">Checkbox:</td>
        <td><input type="checkbox" data-bind="checked: booleanValue" /></td>
    </tr>
    <tr>
        <td class="label">Drop-down list:</td>
        <td><select data-bind="options: optionValues, value: selectedOptionValue"></select></td>
    </tr>
    <tr>
        <td class="label">Multi-select drop-down list:</td>
        <td><select multiple="multiple" data-bind="options: optionValues, selectedOptions: multipleSelectedOptionValues"></select></td>
    </tr>
    <tr>
        <td class="label">Radio buttons:</td>
        <td>
            <label><input type="radio" value="Alpha" data-bind="checked: radioSelectedOptionValue" />Alpha</label>
            <label><input type="radio" value="Beta" data-bind="checked: radioSelectedOptionValue" />Beta</label>
            <label><input type="radio" value="Gamma" data-bind="checked: radioSelectedOptionValue" />Gamma</label>
        </td>
    </tr>
</table>

 

 源代码:View Model

var viewModel = {
    stringValue : ko.observable("Hello"),
    passwordValue : ko.observable("mypass"),
    booleanValue : ko.observable(true),
    optionValues : ["Alpha", "Beta", "Gamma"],
    selectedOptionValue : ko.observable("Gamma"),
    multipleSelectedOptionValues : ko.observable(["Alpha"]),
    radioSelectedOptionValue : ko.observable("Beta")
};
ko.applyBindings(viewModel);

 

http://www.bkjia.com/jQuery/1102786.htmlwww.bkjia.comtruehttp://www.bkjia.com/jQuery/1102786.htmlTechArticle学习笔记,2015学习笔记 参考:
http://www.cnblogs.com/TomXu/archive/2011/11/21/2257154.html
http://knockoutjs.com/documentation/introduction.html
复习:AngularJS的数据…

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图