根据 x、y 位置计算角度。
根据 x、y 位置计算角度。
我正试图根据箭头所要到达的位置计算箭头所需旋转的角度。箭头移动的方向非常复杂,有没有人可以指点一二?
可以在Codepen上查看代码: Codepen
我在这里添加了完整的代码(根据输入进行了编辑)
class Throwable { constructor(){ this.throwObject = null; this.canDrag = null; this.initialDiffX = 0; this.initialDiffY = 0; this.previousX = 0; this.previousY = 0; this.intervalCounter = 0; } set x(input) { this.throwObject.style.left = input + 'px'; } set y(input) { this.throwObject.style.top = input + 'px'; } set rotation(input) { this.throwObject.style.transform = `rotate(${input}deg)`; } init(){ this.throwObject = document.querySelector('.throwable'); this.throwObject.addEventListener('mousedown', this.activateDrag.bind(this)); this.throwObject.addEventListener('mouseup', this.deactivateDrag.bind(this)); document.addEventListener('mousemove', this.drag.bind(this)); } activateDrag(event) { this.canDrag = true; this.initialDiffX = event.clientX - this.throwObject.offsetLeft; this.initialDiffY = event.clientY - this.throwObject.offsetTop; } deactivateDrag() { this.canDrag = false; } drag(event) { if(this.canDrag === true) { if(this.intervalCounter >= 30) { this.intervalCounter = 0; } if(this.intervalCounter === 0) { this.previousX = event.clientX; this.previousY = event.clientY; } this.intervalCounter++; this.y = event.clientY- this.initialDiffY; this.x = event.clientX - this.initialDiffX; this.rotation = this.angle(event.clientX, event.clientY, this.previousX, this.previousY); } } angle(ex, ey, cx, cy) { var dy = ey - cy; var dx = ex - cx; return Math.atan2(dy, dx) * 180 / Math.PI + 90; } // Untility log(logObject) { let logStr = ''; for(let key in logObject) { logStr += `${key}: ${logObject[key]} `; } document.getElementById('log').innerHTML = logStr; } } let throwable = new Throwable(); throwable.init();
我在比较两个不同值时犯了一个错误,我已经修复了它,现在它效果比之前好多了,只是有时候还有些奇怪的行为,好像不知道在某些点上该往哪里走。不过总体来说还是比之前好多了。
admin 更改状态以发布 2023年5月19日
当你调用this.angle()
时,你通过px
和py
两次直接给它this.throwObject.offset...
:
let px = this.throwObject.offsetLeft; let py = this.throwObject.offsetTop; this.rotation = this.angle(this.throwObject.offsetLeft, this.throwObject.offsetTop, px, py)
这将导致angle()
中的dx
和dy
都为0
,使Math.atan2()
的结果不可预测。
我不确定你的代码的其余部分,但也许你的意思是这样调用angle()
:
this.rotation = this.angle(this.x, this.y, px, py);