gpt4 book ai didi

javascript - 如何让眼睛跟随物体?

转载 作者:行者123 更新时间:2023-12-04 13:26:58 26 4
gpt4 key购买 nike

我不完全确定我的代码有什么问题。眼睛(虹膜)似乎被锁定在眼睛的右下 Angular ,并在那个固定位置上旋转。我查看了在线教程并尝试了各种代码,但似乎都不起作用。我想实现的最终目标是让眼睛跟随给定的块。
先感谢您!

window.addEventListener('mousemove', eyeball);
function eyeball() {
const eye = document.querySelectorAll('.eye');
eye.forEach(function(eye){
let x = (eye.getBoundingClientRect().left) + (eye.clientWidth / 2);
let y = (eye.getBoundingClientRect().top) + (eye.clientHeight / 2);

let radian = Math.atan2(event.pageX - x, event.pageY - y);
let rotation = (radian * (180 / Math.PI) * -1) + 270;
eye.style.transform = "rotate("+rotation+"deg)";
});
}
.eye-container {
position: absolute;
display: flex;
justify-content: center;
width: 100%;
margin-top: 20px;
background: pink;
}

.eyeball{
position: relative;
width: 100px;
height: 90px;
border-radius: 50%;
background: white;
margin-right: 20px;
box-shadow: inset 0 0 5px black;
overflow: hidden;
}

.pupil{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 50px;
height: 45px;
border-radius: 50%;
background: black;
border: 10px solid purple;
box-sizing: border-box;
}

.block{
position: absolute;
top: 50%;
width: 100px;
height: 100px;
background: red;
}
<section class="eye-container">
<div class="eyelids eyelid-left"></div>
<div class="eyelids eyelid-right"></div>
<div class=" eyeball left-eye">
<div class=" eye pupil left-pupil"></div>
</div>
<div class="eyeball right-eye">
<div class="eye pupil right-pupil"></div>
</div>
</section>

<div class="block"></div>

最佳答案

你想要的可能更像这样。这会将瞳孔转换到位,使其具有“跟随外观”。

function eyeball(target_x, target_y) {
const eye = document.querySelectorAll('.eye');
eye.forEach(function(eye){
let x = (eye.getBoundingClientRect().left) + (eye.clientWidth / 2);
let y = (eye.getBoundingClientRect().top) + (eye.clientHeight / 2);
let radian = Math.atan2(target_x - x, target_y - y);
let transform_x = Math.round(Math.sin(radian) * 100);
let transform_y = Math.round(Math.cos(radian) * 100);
eye.style.transform = "translate(" + transform_x + "%, " + transform_y + "%)";
});
}
您还需要更改瞳孔的初始样式以获得位置变化的正确偏移量。
.pupil{
margin-left: 25px;
margin-top: 25px;
width: 50px;
height: 45px;
border-radius: 50%;
background: black;
border: 10px solid purple;
box-sizing: border-box;
}

关于javascript - 如何让眼睛跟随物体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67917517/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com