Poggins
Poggins

Reputation: 41

Need help making a semi-simple javascript game

I'm trying to build a game in Javascript but cannot seem to find tutorials or source code that are right for what I want to do, they are either too simple or too complicated.

In theory, all I need to know is how to produce an object on-screen (ie a bullet) by pressing an on-screen button, make that object move across the screen, and eventually collide with something.

I thought the first two parts would be relatively easy, but I cannot find out how to do them. I'm starting to think this will be a lot more complicated than I first believed, but I hope this isn't the case.

So yeah, any help with helping me get this project off the ground would be much appreciated!

Upvotes: 0

Views: 329

Answers (1)

Boundless
Boundless

Reputation: 2464

 <html>
<script type="text/javascript">
var bulletMovement;
var bulletCounter = 0;

function startGame(){
// set the location of the bullet in the style tag
var newNode = document.createElement("<img src=\"bullet.jpg\" alt=\"bullet\" width:20px height:20px; style=\"position:absolute; left:200px;\" />");
newNode.id = "bullet" + bulletCounter; // unique id to keep track of bullets
document.getElementById("game").appendChild(newNode);
bulletMovement = window.setInterval("moveBullet(" + bulletCounter++ +")",100); // move bullet every 1/10 second
}

function moveBullet(bulletId){
var left = parseInt(document.getElementById("bullet"+bulletId).style.left);
if(left < -20)
    window.clearInterval(bulletMovement); // stop moving the bullet if it is off the screen
    document.getElementById("bullet"+bulletId).style.left = left - 5;
}

</script>
<body onload="startGame()">

<div id="game" style="width:200px; height:200px; border-style:solid; border-width:1px; border-color:black">&nbsp;</div>
</body>
</html>

Upvotes: 1

Related Questions