通过Haxe脚本实现相机的移动和旋转功能,参考代码如下:
// 相机旋转,设定lookAt目标示例
package arm;
import iron.math.Quat;
import iron.object.Object;
import iron.Scene;
import iron.math.Vec4;
class MyTrait extends iron.Trait {
var cam: Object = null;
var lookat = new Vec4(5, 5, 5);
var q = new Quat();
public function new() {
super();
notifyOnInit(function() {
cam = Scene.active.getChild("Camera");
lookat = Scene.active.getChild("Cube").transform.loc;
});
notifyOnUpdate(function() {
var loc = cam.transform.loc;
var angleXY = this.getAngleXY(lookat, loc);
var angleZ = this.getAngleZ(lookat, loc);
q.fromEuler(0.5*Math.PI+angleZ, 0, angleXY-0.5*Math.PI);
cam.transform.rot.setFrom(q);
cam.transform.buildMatrix();
});
// notifyOnRemove(function() {
// });
}
// 计算绕Z轴旋转的角度差
private function getAngleXY(lookAt: Vec4, cameraLoc: Vec4) {
var xd = Math.abs(lookAt.x - cameraLoc.x);
var zd = Math.abs(lookAt.y- cameraLoc.y);
var angle = 0.0;
if (lookAt.x > cameraLoc.x) {
if (lookAt.y >= cameraLoc.y) {
// quadrant 1
angle = Math.atan2(zd, xd);
} else {
// quadrant 4
angle = 2 * Math.PI - Math.atan2(zd, xd);
}
} else {
if (lookAt.y >= cameraLoc.y) {
// quadrant 2
angle = Math.PI - Math.atan2(zd, xd);
} else {
// quadrant 3
angle = Math.PI + Math.atan2(zd, xd);
}
}
return angle;
}
// 计算Z轴方向的角度差
private function getAngleZ(lookAt: Vec4, cameraLoc: Vec4) {
var dif = new Vec4().subvecs(lookAt, cameraLoc);
var delZ = lookAt.z - cameraLoc.z;
return Math.atan2(delZ, Math.sqrt(dif.x*dif.x+dif.y*dif.y));
}
}
可以正常运行,不过在渲染过程中,似乎会出现场景闪烁的现象,欢迎大牛们指导指导。