My personal idea is to obtain the coordinates of the mouse and the coordinates of the car when clicking, calculate the angle tan between the straight line formed by these two points and the X-axis, and use setInterval() to increase the X-axis direction of the car by 1px, Y every millisecond. The axis increases (1*tan)px;
But there is a problem with the code implementation, and the calculated tan value keeps changing.
I’m very confused. I don’t know if it’s a problem with my thinking or a problem with the code. I’m begging all the experts to help me figure it out. I hope there are corresponding reference codes~
(I Googled it, but I couldn’t find a solution. Tutor I asked you to hand in the code tomorrow morning, I really don’t know what to do)
$(document).ready(function() {
// 获取鼠标坐标
$(document).mousemove(function(e) {
mouse.X = e.clientX;
mouse.Y = e.clientY;
});
$(document).click(function() {
// 获取点击时鼠标垫的位置
var mX = mouse.X;
var mY = mouse.Y;
// 获取飞机之前的位置
var airX = $("#air").css("left");
var airY = $("#air").css("top");
// 处理字符串中的px并转换为数字
airX = airX.substring(0, airX.length - 2);
airY = airY.substring(0, airY.length - 2);
airX = Number(airX);
airY = Number(airY);
// 计算飞机与鼠标连线与X轴构成的夹角
var tan = (mX - airX) / (mY - airY);
console.log(tan)
setInterval(function() {
main(mX, mY,tan);
}, 1)
})
});
// 创建鼠标对象
var mouse = {
X: 0,
Y: 0
}
function main(mX, mY,tan) {
// 计算每毫秒小飞机前进的距离
// 设定X轴前进1px,Y轴前进1*tan px
var mX = mX + 1;
var mY = mY + tan;
ff(mX + "px", mY + "px");
}
function ff(X, Y) {
$("#air").css({ "top": X });
$("#air").css({ "left": Y });
}
Questions
Workable code
First position the car, then get the position clienX under the mouse point, use this clientX to subtract the $('#car')offset().left of the car, determine the direction based on the positive and negative values, determine the distance based on the absolute value, and then modify Just the left side of the car will do
There is no need to use such fancy formulas. For uniform motion, multiply the speed by time to get the distance of each movement
Current x, y
Target x', y'
Speed v
Time to target t= (x'- x)/v
interval time interval dT
next position next x" = x + dT*v, y"=..
Just move the position to x", y" in interval
The logic seems okay, but if you want to calculate the tan of the angle between the direction and the X-axis, it should be
That’s right, you wrote it backwards...