dcsimg
www.webdeveloper.com
Results 1 to 4 of 4

Thread: Collision detection with enemy

  1. #1
    Join Date
    Mar 2015
    Posts
    3

    Collision detection with enemy

    Hello,

    I'm making a game but cannot figure out the collision. I have two scripts, a enemy script and a player script.

    Code:
    // get a refrence to the canvas and its context
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    
    // newly spawned objects start at Y=25
    var spawnLineY = 25;
    
    // spawn a new object every 1500ms
    var spawnRate = 2000;
    
    
    // when was the last object spawned
    var lastSpawn = -1;
    
    // this array holds all spawned object
    var objects = [];
    
    // save the starting time (used to calc elapsed time)
    var startTime = Date.now();
    
    //enemy image
    var images = [];
    for (var i = 0; i < 5; i++)
    {
    	images.push(new Image());
    	images[i].src = "enemy" + i + ".png";
    }
    
    var enemyStats = [
    	new Enemy(2),
    	new Enemy(4),
    	new Enemy(6),
    	new Enemy(8),
    	new Enemy(10),
    ];
    
    function Enemy(speed)
    {
    	this.speed = speed;
    }
    
    
    //valsnelheid
    var spawnRateOfDescent = 0.50;
    
    // start animating
    
    window.onload = function() 
    {
        animate();
    }
    
    
    function spawnRandomObject() {
    
    // select a random type for this new object
    var t;
    
    // About Math.random()
    // Math.random() generates a semi-random number
    // between 0-1. So to randomly decide if the next object
    // will be A or B, we say if the random# is 0-.49 we
    // create A and if the random# is .50-1.00 we create B
    
    // create the new object
    function Entity()
    {
        // set this objects type
        //type = t,
        // set x randomly but at least 15px off the canvas edges
        this.x = Math.random() * (canvas.width - 30) + 15;
        // set y to start on the line where objects are spawned
        this.y = spawnLineY;
    	
    	// give random image
    	this.randomValue = Math.floor(Math.random()*images.length);
        this.image = images[this.randomValue];
    	this.enemy = enemyStats[this.randomValue];
    }
    
    // add the new object to the objects[] array
    objects.push(new Entity());
    }
    
    
    function animate() {
    
    // get the elapsed time
    var time = Date.now();
    
    // see if its time to spawn a new object
    if (time > (lastSpawn + spawnRate)) {
        lastSpawn = time;
        spawnRandomObject();
    }
    
    // request another animation frame
    requestAnimationFrame(animate);
    
    // clear the canvas so all objects can be 
    // redrawn in new positions
    
    // draw the line where new objects are spawned
    ctx.beginPath();
    ctx.moveTo(0, spawnLineY);
    ctx.lineTo(canvas.width, spawnLineY);
    ctx.stroke();
    
    // move each object down the canvas
    for (var i = 0; i < objects.length; i++) 
    	{
    		var object = objects[i];
    		object.y += object.enemy.speed;
    		ctx.drawImage(object.image, object.x, object.y, 30, 30);	
    	}
    }
    Code:
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    
    var playerX = 0,  //initial x
        playerY = 50,  // initial y
        velY = 0,
        velX = 0,
        playerSpeed = 2, // max speed
        friction = 0.98, // friction
        keys = [];
    	
    	
    var img = new Image();
    img.src = "Player0.png";
    
    function update() {
    
        // check the keys and do the movement.
        if (keys[38]) {
            if (velY > -playerSpeed) {
                velY--;
            }
        }
    
        if (keys[40]) {
            if (velY < playerSpeed) {
                velY++;
            }
        }
        if (keys[39]) {
            if (velX < playerSpeed) {
                velX++;
            }
        }
        if (keys[37]) {
            if (velX > -playerSpeed) {
                velX--;
            }
        }
    
    
        // apply some friction to y velocity.
        velY *= friction;
        playerY += velY;
    
        // apply some friction to x velocity.
        velX *= friction;
        playerX += velX;
    
        // bounds checking
        if (playerX >= 200) {
            playerX = 200;
        } else if (playerX <= -200) {
            playerX = -200;
        }
    
        if (playerY > 70) {
            playerY = 70;
        } else if (playerY <= -200) {
            playerY = -200;
        }
    	//console.log(playerY);
    
        // do the drawing
        ctx.clearRect(0, 0, 1000, 1000);
        ctx.beginPath();
    	ctx.drawImage(img, playerX + 250, playerY + 500)
    
        setTimeout(update, 10);
    }
    
    update();
    
    // key events
    document.body.addEventListener("keydown", function (e) {
        keys[e.keyCode] = true;
    });
    document.body.addEventListener("keyup", function (e) {
        keys[e.keyCode] = false;
    });
    i'm kind of stuck how to do the collision, i hope someone can help me with this? I'm very new to javascript

  2. #2
    Join Date
    Mar 2015
    Posts
    14
    How about... (in player script)

    Code:
        //console.log(playerY);
        
        var playerOffsetX = 250;
        var playerOffsetY = 500;
    
        // loop objects to detect collision with player
        for (var i in objects) {
            var o = objects[i];
    
            var cx = img.width / 2;
            var cy = img.height / 2;
    
            var pcx = (playerX + playerOffsetX) + (cx);
            var pcy = (playerY + playerOffsetY) + (cy);
    
            if ((pcx > (o.x - cx) && (pcx) < (o.x + cx)) &&
               ((pcy > (o.y - cy) && (pcy) < (o.y + cy))))
                alert('hit');
        }
    
        // do the drawing
        ctx.clearRect(0, 0, 1000, 1000);
        ctx.beginPath();
        ctx.drawImage(img, playerX + playerOffsetX , playerY + playerOffsetY )

  3. #3
    Join Date
    Mar 2015
    Posts
    3
    Quote Originally Posted by nplus View Post
    How about... (in player script)

    Code:
        //console.log(playerY);
        
        var playerOffsetX = 250;
        var playerOffsetY = 500;
    
        // loop objects to detect collision with player
        for (var i in objects) {
            var o = objects[i];
    
            var cx = img.width / 2;
            var cy = img.height / 2;
    
            var pcx = (playerX + playerOffsetX) + (cx);
            var pcy = (playerY + playerOffsetY) + (cy);
    
            if ((pcx > (o.x - cx) && (pcx) < (o.x + cx)) &&
               ((pcy > (o.y - cy) && (pcy) < (o.y + cy))))
                alert('hit');
        }
    
        // do the drawing
        ctx.clearRect(0, 0, 1000, 1000);
        ctx.beginPath();
        ctx.drawImage(img, playerX + playerOffsetX , playerY + playerOffsetY )
    Hi nplus, thank you for taking the time to help me! I have a problem if I put that code in the script, it gives a error Uncaught ReferenceError: objects is not defined. Which is correct I guess because objects is not a var in the Player script. But I can't really find how I get access to this var in the enemy.js file. I hope someone can help me with that?

  4. #4
    Join Date
    Mar 2015
    Posts
    3
    Ow, I can't edit the post anymore it seems, I figured it out, just needed to change var I in objects to:

    var I in window.objects.

    Thank you very much for the quick response!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles