摘要
你是否困惑於 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~~
源碼在我的微信公衆號回覆關鍵詞【小鴨移動】即可獲得