hello everyone hope you guys are having a great day! so, i am building a simple game where I use a custom-made cursor as the aim for shooting div elements moving around the screen as the enemies and when i apply the "pointerdown" event i want the enemy to change its color. however, every time i hover over the enemy the cursor falls behind witch i don't understand why, and when i use the z-index property it will prevent the "pointerdown" event from firing. if some cool OG programmer can help me, it would mean a lot to me.
style
* {
margin: 0;
padding: 0;
cursor: none;
}
.aim {
position: absolute;
background: black;
width: 10px;
height: 10px;
border-radius: 50%;
transform: translate(-50%, -50%);
}
.enemy {
position: absolute;
border: 3px solid black;
background-color: blue;
width: 50px;
height: 50px;
}
javascript
const body = document.body;
const aim = document.createElement("div");
const enemy = document.createElement("div");
body.appendChild(aim);
body.appendChild(enemy);
aim.classList.add("aim");
enemy.classList.add("enemy");
let enemy_X_position = 0;
let enemy_Y_position = 0;
let enemy_X_distance = 1;
let enemy_Y_distance = 1;
function Flight()
{
enemy.style.left = enemy_X_position "px";
enemy.style.top = enemy_Y_position "px";
}
setInterval(function()
{
enemy_X_position = enemy_X_distance;
enemy_Y_position = enemy_Y_distance;
if ((enemy_X_position enemy.offsetWidth) >= window.innerWidth || enemy_X_position <= 0)
enemy_X_distance = -enemy_X_distance;
if ((enemy_Y_position enemy.offsetHeight) >= window.innerHeight || enemy_Y_position <= 0)
enemy_Y_distance = -enemy_Y_distance;
Flight();
},1000/60)
window.onmousemove = function()
{
aim.style.left = event.pageX "px";
aim.style.top = event.pageY "px";
}
enemy.onpointerdown = function()
{
event.target.style.background = "red";
}
enemy.onpointerup = function()
{
event.target.style.background = null;
}
CodePudding user response:
Update
The event is not triggering because pointerdown
was received by aim
when it sits on top of enemy
.
To solve this, add pointer-events: none
on aim
class to prevent it from being the target of a pointer event.
Hope this will help!
.aim {
position: absolute;
background: black;
width: 10px;
height: 10px;
border-radius: 50%;
transform: translate(-50%, -50%);
pointer-events: none;
}
Original
Perhaps an over simplified solution, but it seems that if you reverse the order of appendChild
, the aim
should be stacked over enemy
without additional styling.
Example:
body.appendChild(enemy);
body.appendChild(aim);
Because both elements are child of body
, Unless there is other styling that override this stacking, the later one should be on top.