cocos3.8.2版本,时间24.5.15
1.前言
记录而已本身菜鸡
准备工作:地面和人物都得挂上碰撞体和刚体(要不然碰撞检测会报错):
人物的刚体和碰撞体要进行下面两个设置:要不然会发现碰撞检测不触发或者人往墙上跳
会粘着墙,
对于地面墙体的刚体进行下面设置节省资源(并且让它们不动):
2..cocos并没有像unity那样有Horizontal和Vertical那样简便的控制
(下面是我的代码,直接CV就好了,懒得再修改说明了,自己看吧)
private isJump:boolean = true;//是否在跳跃
private selfBody:RigidBody2D = null;//自己的刚体组件
private jpMoveArray:Array<number> = [];//键盘移动Key数组,其实就AD键而已,
start() {
let holdCollider = this.node.getComponent(Collider2D);
input.on(Input.EventType.KEY_DOWN,this.onKeyDown, this);//键盘按下
// input.on(Input.EventType.KEY_PRESSING,this.onKeyPressing, this);//键盘按着
input.on(Input.EventType.KEY_UP,this.onKeyUp, this);//键盘抬起
holdCollider.on(Contact2DType.BEGIN_CONTACT,this.onBeginContact, this);
holdCollider.on(Contact2DType.END_CONTACT,this.onEndContact, this);
this.selfBody = this.node.getComponent(RigidBody2D);
}
update(deltaTime: number) {
if (this.jpMoveArray.length > 0) {
let lv = this.selfBody.linearVelocity;//获取刚体的线性速度
// 数组中只有AD的key,所有不是往左就是往右
if (this.jpMoveArray[this.jpMoveArray.length - 1] == KeyCode.KEY_A) {
// 向左移动
lv.x = -8;
}else{
// 向右移动
lv.x = 8;
}
this.selfBody.linearVelocity = lv;
}else{
// 停止运动
let lv = this.selfBody.linearVelocity;
lv = new Vec2(0, lv.y);
this.selfBody.linearVelocity = lv;
}
}
//按下时监听
onKeyDown(event:EventKeyboard){
// 按下A键
if (event.keyCode == KeyCode.KEY_A) {
this.AddJpMove(KeyCode.KEY_A);
}else if(event.keyCode == KeyCode.KEY_D){
this.AddJpMove(KeyCode.KEY_D);
}else if(event.keyCode == KeyCode.KEY_W && !this.isJump){
let lv = this.selfBody.linearVelocity;
lv.y = 16;
this.selfBody.linearVelocity = lv;
}
}
// 按着时监听
// onKeyPressing(event:EventKeyboard){
// console.log(event.keyCode);
// if (event.keyCode == KeyCode.KEY_A) {
// let lv = this.selfBody.linearVelocity;
// lv.x = -8;
// this.selfBody.linearVelocity = lv;
// }else if(event.keyCode == KeyCode.KEY_D){
// let lv = this.selfBody.linearVelocity;
// lv.x = 8;
// this.selfBody.linearVelocity = lv;
// }
// }
// 松开时监听
onKeyUp(event:EventKeyboard){
if (event.keyCode == KeyCode.KEY_A) {
this.SpliceJpMove(KeyCode.KEY_A);
}else if(event.keyCode == KeyCode.KEY_D){
this.SpliceJpMove(KeyCode.KEY_D);
}
}
// 开始碰撞时触发
onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D){
this.isJump = false;
}
// 结束碰撞时触发
onEndContact(selfCollider: Collider2D, otherCollider: Collider2D){
this.isJump = true;
}
/**添加键盘移动数组元素*/
private AddJpMove(key:number){
// 当数组没有包含键盘输入A时
if (this.jpMoveArray.indexOf(key) == -1) {
this.jpMoveArray.push(key);
}
}
/**删除键盘移动数组元素*/
private SpliceJpMove(key:number){
for (let index = 0; index < this.jpMoveArray.length; index++) {
if (this.jpMoveArray[index] == key) {
// 如果包含这个key
this.jpMoveArray.splice(index,1);
break;
}
}
}