cc.Camera組件與物理引擎官方案例
物理引擎及Camera組件的應(yīng)用案例,超級(jí)瑪麗。
一、官方物理引擎案例
1: 準(zhǔn)備好tiled地圖;
2: 為tiled地圖編輯好物理碰撞器;
3: 放出角色,為角色編輯好物理碰撞器;
4: 監(jiān)聽(tīng)鍵盤(pán)消息:
? ? cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.on_key_down.bind(this), this);
? ? cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.on_key_up.bind(this), this);
5: 設(shè)置角色的水平和豎直速度; 豎直600,水平400
6: 設(shè)置cc.Camera組件,設(shè)置Camera跟誰(shuí)玩家;
二、cc.Camera組件
有個(gè)攝像焦點(diǎn)和取景框。在取景框內(nèi)的物體才會(huì)展示出來(lái)。
設(shè)置攝像機(jī)的坐標(biāo)x值跟玩家的坐標(biāo)x值一致即可。
三、應(yīng)用案例-超級(jí)瑪麗

1.玩家運(yùn)動(dòng)控制
新建PlayerCtrl.ts掛載到Player節(jié)點(diǎn)上。
const {ccclass, property} = cc._decorator;
class Direction{
? ?public static RIGHT = 1; ? ?// 向右運(yùn)動(dòng)
? ?public static LEFT = -1; ? ?// 向左運(yùn)動(dòng)
? ?public static NONE = 0; ? ? // 沒(méi)有運(yùn)動(dòng)方向
}
@ccclass
export default class PlayerCtrl extends cc.Component {
? ?@property({tooltip:"超級(jí)瑪麗水平運(yùn)動(dòng)的速度大小"})
vx : number = 200;
? ?private body : cc.RigidBody = null;
? ?private moveDir : number = Direction.NONE;
? ?onLoad () {
this.body = this.node.getComponent(cc.RigidBody);
? ? ? ?cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown.bind(this), this);
? ? ? ?cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp.bind(this), this);
}
? ?onKeyDown(e){
? ? ? ?//console.log(e);
? ? ? ?switch(e.keyCode){
? ? ? ? ? ?case cc.macro.KEY.space :
this.jump();
? ? ? ? ? ? ? ?break;
? ? ? ? ? ?case cc.macro.KEY.left :
this.moveDir = Direction.LEFT;
? ? ? ? ? ? ? ?break;
? ? ? ? ? ?case cc.macro.KEY.right :
this.moveDir = Direction.RIGHT;
? ? ? ? ? ? ? ?break;
? ? ? ? ? ?default:this.moveDir = Direction.NONE;
? ? ? ?}
}
? ?onKeyUp(e){
? ? ? ?switch(e.keyCode){
? ? ? ? ? ?default:this.moveDir = Direction.NONE;
? ? ? ?}
}
? ?jump(){
? ? ? ?let v : cc.Vec2 = this.body.linearVelocity;
? ? ? ?v.y = 400;
this.body.linearVelocity = v;
}
? ?update (dt : number) {
? ? ? ?if(this.moveDir === Direction.NONE){
? ? ? ? ? ?return;
? ? ? ?}
? ? ? ?// 玩家的實(shí)時(shí)速度,有方向的
? ? ? ?let v : cc.Vec2 = this.body.linearVelocity;
? ? ? ?v.x = this.vx * this.moveDir;
this.body.linearVelocity = v;
? ? ? ?// 改變玩家臉的朝向
this.node.scaleX = this.moveDir;
? ?}
}
2.攝像機(jī)跟隨玩家拍攝
新建CameraCtrl.ts掛載到Main Camera節(jié)點(diǎn)上。
const {ccclass, property} = cc._decorator;
@ccclass
export default class CameraCtrl extends cc.Component {
? ?@property({type:cc.Node, tooltip:"攝像機(jī)的跟隨目標(biāo)"})
player : cc.Node = null;
? ?update (dt) {
this.node.x = this.player.x;
? ? ? ?//this.node.setPosition(this.player.getPosition());
? ?}
}
這部分的分享就先到這里,想要觀看其他課程請(qǐng)點(diǎn)擊:
https://bycwedu.vipwan.cn/promotion_channels/630597732