PlayerMovement.ts 脚本挂载到游戏人物上
import { _decorator, Component, Node, Vec3, input, Input, EventTouch } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('Player')
export class Player extends Component {
// 移动速度
@property
speed: number = 5;
private pos: Vec3;
start() {
this.pos = this.node.getPosition();
console.log(`start this.pos: x=${this.pos.x}, y=${this.pos.y}, z=${this.pos.z}`);
// 添加全局触摸事件监听
input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
}
onDestroy() {
// 移除事件监听
input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
}
update(deltaTime: number) {
this.move();
}
move() {
this.node.setPosition(this.pos);
}
onTouchStart(event: EventTouch) {
// 可以在这里处理触摸开始时的逻辑
}
onTouchEnd(event: EventTouch) {
// 可以在这里处理触摸结束时的逻辑
}
onTouchMove(event: EventTouch) {
const delta = event.getDelta();
// 根据手指移动的方向改变位置
this.pos.x += delta.x * this.speed;
this.pos.y += delta.y * this.speed;
}
}
cocos 手游开发,相机跟随游戏人物的移动,摄像机跟随,用typescript写,我用的cocos版本是3.8.5
CameraFollow.ts
import { _decorator, Component, Node, Vec3, Camera } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('CameraFollow')
export class CameraFollow extends Component {
// 游戏人物节点
@property(Node)
target: Node | null = null;
// 相机组件
private camera: Camera | null = null;
start() {
// 获取相机组件
this.camera = this.node.getComponent(Camera);
if (!this.camera) {
console.error('未找到相机组件!');
return;
}
if (!this.target) {
console.error('未指定跟随目标!');
return;
}
}
update(deltaTime: number) {
if (this.target && this.camera) {
const targetPos = this.target.position;
const cameraPos = this.node.position;
// 计算相机应该移动到的位置
const newPos = new Vec3(targetPos.x, targetPos.y, cameraPos.z);
// 更新相机位置
this.node.setPosition(newPos);
}
}
}
使用步骤
- 创建脚本:在 Cocos Creator 里创建一个新的 TypeScript 脚本,把上述代码复制进去。
- 挂载脚本:将脚本挂载到相机节点上。
- 设置属性:在属性检查器中,把
target
属性设置为游戏人物的节点。
代码解释
target
:游戏人物的节点,相机将跟随该节点移动。camera
:相机组件,用于获取和设置相机的位置。start
方法:在脚本开始时,获取相机组件和游戏人物节点,并进行必要的检查。update
方法:在每一帧中,获取游戏人物的位置,计算相机应该移动到的位置,并更新相机的位置。
注意事项
- 此代码假定相机的
z
坐标保持不变,仅在x
和y
方向上跟随游戏人物移动。 - 若你需要平滑的相机跟随效果,可以添加一些插值算法,例如线性插值(Lerp)。