CocosCreator3D之视角移动

摘要

你是否困惑于 CocosCreator3D 的视角与移动?KUOKUO 带你搞定!底部源码相送!

正文

版本说明

使用 CocosCreator3D 的 1.0.1 版本演示。

模型的移动

在二维和三维的移动控制中,对于平面移动,虽然也都是控制两个方向,但是还采用角度计算的方式会出现很多问题,毕竟还有第三个轴。我们要转变思维,从 Math.sin 与 Math.cos 转变为 Vec3 控制。

比如我想让一个物体前进 10 的距离。

let pos = this.node.getPosition();
pos.x += 10;
this.node.setPosition(pos);

但是这样的移动,是沿着 X 轴的移动,如果主角不是看向前方呢?我们还要考虑旋转度。所以要封装一个方法,让 x,y,z 是基于自身方向的。

// 根据自身方向,转化方向
_getDirection (x: number, y: number, z: number) {
	const result = new Vec3(x, y, z);
	math.Vec3.transformQuat(result, result, this.node.getRotation());
	return result;
}

这样,假设我们看向的是 x,z 方向的中间,传入一个 Vec3(1, 0, 0) 方向,就可以返回一个 Vec3(0.7, 0, 0.7) 向量。为什么是 0.7 呢?因为是根号二的一半。

这样,我们利用向量相加,就把位移量加上去了。

const position = this.node.getPosition();
math.Vec3.scaleAndAdd(position, position, this._getDirection(1,0,0), deltaTime * this.speed);
this.node.setPosition(position);

视角的旋转

我在摄像机放在小鸭子管理节点下,如图。

这样摄像机就会一直跟着小鸭子,然后上下视角动摄像机,左右的旋转动小鸭子。

onMouseMove (event: EventMouse) {
    const PI = 3.1415926535;
    if(event.movementX != 0) {
        const rotationY = this.node.getRotation();
        math.Quat.rotateAround(rotationY, rotationY, this._getDirection(0, -1, 0), event.movementX / 5 / 360.0 * PI);
        this.node.setRotation(rotationY);
    }
    if(event.movementY != 0) {
        const rotationX = this.camera.getRotation();
        math.Quat.rotateAround(rotationX, rotationX, this._getDirection(1, 0, 0), event.movementY / 5 / 360.0 * PI);
        this.camera.setRotation(rotationX);
    }
}

结语

看会了吗?让我们一起学习!

O(∩_∩)O~~

源码在我的微信公众号回复关键词【小鸭移动】即可获得

微信公众号

扫描二维码关注公众号,回复: 8794833 查看本文章
发布了120 篇原创文章 · 获赞 133 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/kuokuo666/article/details/103184246