export default class TestAngle extends cc.Component {
@property(cc.Node)
root: cc.Node;
@property(cc.Graphics)
graph: cc.Graphics;
@property(cc.Node)
target: cc.Node;
@property(cc.Label)
angleDes: cc.Label;
start() {
this.node.on(cc.Node.EventType.TOUCH_MOVE,this.onTouchMove,this);
}
onTouchMove(event: cc.Event.EventTouch): void {
let startPos: cc.Vec2 = this.target.convertToWorldSpaceAR(new cc.Vec2(0, 0));
let endPos: cc.Vec2 = event.getLocation();
let dirVec = endPos.sub(startPos);//获得从startPos指向endPos的方向向量
let comVec = new cc.Vec2(1, 0);//计算夹角的参考方向,这里选择x轴正方向
let radian = dirVec.signAngle(comVec);//获得带方向的夹角弧度值(参考方向顺时针为正值,逆时针为负值)
let degree = Math.floor(cc.misc.radiansToDegrees(radian));
console.log("x角度:" + degree)
this.angleDes.node.position = this.root.convertToNodeSpaceAR(endPos);
this.angleDes.string = degree + "°";
let comEnd = new cc.Vec2(startPos.x + 200, startPos.y);
this.drawAngle(startPos, endPos, comEnd);
}
/**
*
* @param startPos 起始点
* @param endPos 终点(对应鼠标点击的点)
* @param comEnd 参照向量的终点
*/
private drawAngle(startPos: cc.Vec2, endPos: cc.Vec2, comEnd: cc.Vec2) {
this.graph.clear();
this.graph.lineWidth = 1;
this.graph.strokeColor = cc.Color.WHITE;
this.graph.moveTo(startPos.x, startPos.y);
this.graph.lineTo(endPos.x, endPos.y);
this.graph.stroke();
this.graph.strokeColor = cc.Color.GREEN;
this.graph.moveTo(startPos.x, startPos.y);
this.graph.lineTo(comEnd.x, comEnd.y);
this.graph.stroke();
}
}