user3150635
user3150635

Reputation: 547

how to listen for a mouse click in a javascript game

I'm designing a game in javascript and I have a function that goes like this:

function handleKeys(mod) {

    if (37 in keysDown || 65 in keysDown) { //left
        player.x -= player.speed * mod; 
    }
    if (38 in keysDown || 87 in keysDown) { //up
        player.y -= player.speed * mod;
    }
    if (39 in keysDown || 68 in keysDown) { //right
        player.x += player.speed * mod;
    }
    if (40 in keysDown || 83 in keysDown) { //down
        player.y += player.speed * mod;

and I want to add another conditional that calls my shoot() function when I click the mouse. How can I write that conditional so that it resembles the code above, because every tutorial I've seen just tells me how to make clickable buttons and requires me to use addEventListener, which I don't think is right for what I'm trying to do.

Upvotes: 0

Views: 1007

Answers (1)

user3587638
user3587638

Reputation:

Use mouse coordinates to tell where the shot is and use this as your html tag:

<html onclick="shoot()">
    <!-- code -->
</html>

You could also use the onclick on your canvas like:

<canvas onclick="shoot()" id="game_pad"></canvas>

Upvotes: 1

Related Questions