cc.Camera组件与物理引擎官方案例
物理引擎及Camera组件的应用案例,超级玛丽。
一、官方物理引擎案例
1: 准备好tiled地图;
2: 为tiled地图编辑好物理碰撞器;
3: 放出角色,为角色编辑好物理碰撞器;
4: 监听键盘消息:
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: 设置角色的水平和竖直速度; 竖直600,水平400
6: 设置cc.Camera组件,设置Camera跟谁玩家;
二、cc.Camera组件
有个摄像焦点和取景框。在取景框内的物体才会展示出来。
设置摄像机的坐标x值跟玩家的坐标x值一致即可。
三、应用案例-超级玛丽

1.玩家运动控制
新建PlayerCtrl.ts挂载到Player节点上。
const {ccclass, property} = cc._decorator;
class Direction{
public static RIGHT = 1; // 向右运动
public static LEFT = -1; // 向左运动
public static NONE = 0; // 没有运动方向
}
@ccclass
export default class PlayerCtrl extends cc.Component {
@property({tooltip:"超级玛丽水平运动的速度大小"})
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;
}
// 玩家的实时速度,有方向的
let v : cc.Vec2 = this.body.linearVelocity;
v.x = this.vx * this.moveDir;
this.body.linearVelocity = v;
// 改变玩家脸的朝向
this.node.scaleX = this.moveDir;
}
}
2.摄像机跟随玩家拍摄
新建CameraCtrl.ts挂载到Main Camera节点上。
const {ccclass, property} = cc._decorator;
@ccclass
export default class CameraCtrl extends cc.Component {
@property({type:cc.Node, tooltip:"摄像机的跟随目标"})
player : cc.Node = null;
update (dt) {
this.node.x = this.player.x;
//this.node.setPosition(this.player.getPosition());
}
}
这部分的分享就先到这里,想要观看其他课程请点击:
https://bycwedu.vipwan.cn/promotion_channels/630597732