【发布时间】:2021-04-30 18:23:44
【问题描述】:
我基本上想用鼠标对角移动蜘蛛,就像用鼠标进行 8 向移动一样,但我不确定这可能吗?我的想法:如果 x 和 y 坐标同时改变,那么它是对角线运动,对吗?我在对角线鼠标移动上找不到任何东西。
HTML
<html>
<head>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.3/css/all.css"
</head>
<body>
<div class="spiderweb"><i id="cursor" class="fas fa-spider"></i></div>
</body>
</html>
CSS
body {
cursor: none;
display:flex;
justify-content:center;
align-items:center;
}
.spiderweb {
width: 400px;
height: 400px;
background: aliceblue;
background: url(https://cdn.pixabay.com/photo/2016/03/31/20/12/spider-web-1295590_1280.png);
background-repeat: none;
background-size: cover;
}
.fa-spider {
font-size: 2.5em;
}
#cursor {
position: absolute;
/* transition-duration: 0.1s; */
top: 0px;
left: 0px;
filter: drop-shadow(1px 2px 2px rgba(0, 0, 0, 0.4));
}
JS
//Get cursor element , set store x and y position//
let mouseCursor = document.querySelector("#cursor");
var oldx = 0;
var oldy = 0;
var direction = "";
//listen to cursor move and get page coordinates
window.addEventListener("mousemove", function (event) {
var yPos = event.pageY;
var xPos = event.pageX;
//set cursor to match page coordinates
mouseCursor.style.top = yPos + "px";
mouseCursor.style.left = xPos + "px";
//determine direction cursor is moving
if (xPos > oldx) {
direction = "right";
oldx = xPos;
mouseCursor.style.transform = "rotate(90deg)";
} else if (xPos < oldx) {
direction = "left";
oldx = xPos;
mouseCursor.style.transform = "rotate(-90deg)";
} else if (yPos > oldy) {
direction = "down";
oldy = yPos;
mouseCursor.style.transform = "rotate(180deg)";
} else if (yPos < oldy) {
direction = "up";
oldy = yPos;
mouseCursor.style.transform = "rotate(0deg)";
}
console.log(direction);
链接到我的代码笔示例 SpiderCursor
【问题讨论】:
-
我可以提供答案,但在我找到答案之前,请查找游戏的 2D 矢量数学。非常简单的东西,尽管听起来很简单。
标签: javascript events cursor mousemove diagonal