<九>相机跟随

实现相机跟随Player让整个游戏节奏更完整。

如果单纯的跟随角色,将MainCamera拖到Player节点下即可。但这里会有一个问题,子节点会随着父节点的变化(旋转/位移/缩放)而变化,如果是过山车可能比较适合,但在该场景中,只需要让相机跟随玩家位移,而不需要其他旋转。

脚本驱动

新建一个脚本叫FollowTarget
拖拽到主相机上
编辑脚本

import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('FollowTarget')
export class FollowTarget extends Component {
    @property(Node)
    target_node: Node = null;
    start() {

    }

    update(deltaTime: number) {
        this.node.position = this.target_node.position;
    }
}


运行预览,发现画面在变换,但是地面、player都看不到。
这是因为相机的位置和Player的位置是一样的。
实际环境,相机应该在Player的后上方一些,就如相机跟随前调试的相机位置。
这里修改一下脚本:
创建一个引用表示相机和Player之间的偏移

import { _decorator, Component, Node, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('FollowTarget')
export class FollowTarget extends Component {
    @property(Node)
    target_node: Node = null;
    @property(Vec3)
    offset: Vec3 = new Vec3(0, 0, 0);

    _tempVec: Vec3 = new Vec3();
    start() {

    }

    update(deltaTime: number) {
        this.target_node.getPosition(this._tempVec);
        this._tempVec.add(this.offset);
        this.node.position = this._tempVec;
    }
}


运行预览
可以看到,相机跟随Player移动了,Player旋转时相机并没有跟随旋转。

posted @ 2024-12-17 14:08  EricShx  阅读(71)  评论(0)    收藏  举报