最近开发了一个恐龙岛类型小demo,就详细介绍一个功能的实现即原理
1.角色的移动
起始就是用了引擎自带的物理系统,
我们给节点挂上 刚体 在挂上刚体box 就可以啦;
后面我们只要在脚本当中 获取 RigidBody (刚体组件)
注意:一定要在import 加上RigidBody
this.rigidbody = this.node.getComponent(RigidBody);
然后我们就可以控制刚体了
this.rigidbody.setLinearVelocity(v3(0, 0,1));
我们可以给刚体一个速度 那么他就会移到
2.如何转向
第一步计算两点角度
getAngle(start:any, end:any){
//计算出朝向
var dx = end.x - start.x;
var dy = end.z - start.z;
var dir = v2(-dx,dy);
//根据朝向计算出夹角弧度
var angle = dir.signAngle(v2(1,0));
//将弧度转换为欧拉角
var degree = angle / Math.PI * 180;
return -degree
}
拿到角度后 我们就可以用角度换成 x,z 方向的速度
let OAngle = angle / 180 * Math.PI;
let x = Math.cos(OAngle)*this.getYdsd();
let y = Math.sin(OAngle)*this.getYdsd();
this.rigidbody.setLinearVelocity(v3(-x, 0,y));
这样就可以转向移动了
我一般会封装一个move 函数 这样所以的 移动相关都放在move函数里面
- 相机跟随转向
一般我会把相机放到一个节点
然后我们只要让这个节点的3纬坐标和恐龙的坐标一样就可以了
转向
我们在相机上挂载一个脚本
import { _decorator, Component, Node,find,v3 } from ‘cc’;
const { ccclass, property } = _decorator;
@ccclass(‘gameCamera’)
export class gameCamera extends Component {
start() {
this.bdnode = null;
this.h=2;
}
update(deltaTime: number) {
if(!this.bdnode)
{
return false;
}
this.Aposi = v3(this.bdnode.getPosition().x,0,this.bdnode.getPosition().z);
this.node.setPosition(this.Aposi);
}
}
但是在移动的时候要加上这个角度就可以了
angle = (angle+find(‘Canvas/ui/shijiao’).getComponent(‘shijiao’).CAngle);
其它的没有什么了,都是一些简单的东西