My collision detection isn't working

有些话、适合烂在心里 提交于 2019-12-13 08:56:12

问题


I'm trying to make a simple game where you are pacman and need to collect cherries while avoiding the ghosts. I can't seem to figure out how to check for collision and i've tried searching through other questions but none of them work. Here is my code:

<script language="javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
<script language="javascript">

var pacman = {
    speed: 256,
    x: 0,
    y: 0,
    height: 50,
    width: 50
};
var blinky = {
    x: 0,
    y: 0
};
var inky = {
    x: 0,
    y: 0
};
var pinky = {
    x: 0,
    y: 0
};
var clyde = {
    x: 0,
    y: 0
};
var cherry = {
    x: 100,
    y: 100,
    height: 56,
    width: 56
};
var score = 0;
var y = $(window).width() - 50;
var lives = 3;


/*
var reset = function () {
    cherry.x = 56 + (Math.random() * (window.width - 112));
    cherry.y = 56 + (Math.random() * (window.height - 112));
    $('#cherry').animate({left: cherry.x, top: cherry.y},0);
};



var update = function (modifier) {
    if (
        ((pacman.y + pacman.height) < (cherry.y)) ||
        (pacman.y > (cherry.y + cherry.height)) ||
        ((pacman.x + pacman.width) < cherry.x) ||
        (pacman.x > (cherry.x + cherry.width))
    ) {
        reset();
    }
};*/


if (pacman.x < cherry.x + cherry.width &&
   pacman.x + pacman.width > cherry.x &&
   pacman.y < cherry.y + cherry.height &&
   pacman.height + pacman.y > cherry.y) {
    console.log(hi);
}



$(document).ready(function(){
    $('#cherry').animate({left: cherry.x, top: cherry.y},0);
});
$(document).ready(function(){
    $('#pacman').animate({left: '' + y + '', top: "0"},0);
});



$(document).ready(function(){
    animateDiv();
    
});

function makeNewPosition(){
    
    // Get viewport dimensions (remove the dimension of the div)
    var h = $(window).height() - 30;
    var w = $(window).width() - 30;
    
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    
    return [nh,nw];    
    
}

function animateDiv(){
    var newq = makeNewPosition();
    var oldq = $('#blinky').offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);
    
    $('#blinky').animate({ top: newq[0], left: newq[1] }, speed, function(){
      animateDiv();        
    });
    
};

function calcSpeed(prev, next) {
    
    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);
    
    var greatest = x > y ? x : y;
    
    var speedModifier = 0.1;

    var speed = Math.ceil(greatest/speedModifier);

    return speed;

}

$(document).ready(function(){
    animateDivv();
    
});

function makeNewPositionn(){
    
    // Get viewport dimensions (remove the dimension of the div)
    var h = $(window).height() - 30;
    var w = $(window).width() - 30;
    
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    
    return [nh,nw];    
    
}

function animateDivv(){
    var newq = makeNewPositionn();
    var oldq = $('#inky').offset();
    var speed = calcSpeedd([oldq.top, oldq.left], newq);
    
    $('#inky').animate({ top: newq[0], left: newq[1] }, speed, function(){
      animateDivv();        
    });
    
};

function calcSpeedd(prev, next) {
    
    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);
    
    var greatest = x > y ? x : y;
    
    var speedModifier = 0.1;

    var speed = Math.ceil(greatest/speedModifier);

    return speed;

}

$(document).ready(function(){
    animateDivvv();
    
});

function makeNewPositionnn(){
    
    // Get viewport dimensions (remove the dimension of the div)
    var h = $(window).height() - 30;
    var w = $(window).width() - 30;
    
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    
    return [nh,nw];    
    
}

function animateDivvv(){
    var newq = makeNewPositionnn();
    var oldq = $('#pinky').offset();
    var speed = calcSpeeddd([oldq.top, oldq.left], newq);
    
    $('#pinky').animate({ top: newq[0], left: newq[1] }, speed, function(){
      animateDivvv();        
    });
    
};

function calcSpeeddd(prev, next) {
    
    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);
    
    var greatest = x > y ? x : y;
    
    var speedModifier = 0.1;

    var speed = Math.ceil(greatest/speedModifier);

    return speed;

}

$(document).ready(function(){
    animateeDiv();
    
});

function makeNewwPosition(){
    
    // Get viewport dimensions (remove the dimension of the div)
    var h = $(window).height() - 30;
    var w = $(window).width() - 30;
    
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    
    return [nh,nw];    
    
}

function animateeDiv(){
    var newq = makeNewwPosition();
    var oldq = $('#clyde').offset();
    var speed = calccSpeed([oldq.top, oldq.left], newq);
    
    $('#clyde').animate({ top: newq[0], left: newq[1] }, speed, function(){
      animateeDiv();        
    });
    
};

function calccSpeed(prev, next) {
    
    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);
    
    var greatest = x > y ? x : y;
    
    var speedModifier = 0.1;

    var speed = Math.ceil(greatest/speedModifier);

    return speed;

}



var pressed = false;
$(document).keydown(function(e) {
    if(!pressed){
        width = $(this).width();
        height = $(this).height();
        switch (e.which) {
            case 37:
                $('p').css({'background-image': 'url(pacman-left.png)'})
                $('p').stop().animate({
                    left: '-=' + width * 50
                }, 15000); //left arrow key
                break;
            case 38:
                $('p').css({'background-image': 'url(pacman-up.png)'})
                $('p').stop().animate({
                    top: '-=' + height * 50
                }, 15000); //up arrow key
                break;
            case 39:
                $('p').css({'background-image': 'url(pacman-right.png)'})
                $('p').stop().animate({
                    left: '+=' + width * 50
                }, 15000); //right arrow key
                break;
            case 40:
                $('p').css({'background-image': 'url(pacman-down.png)'})
                $('p').stop().animate({
                    top: '+=' + height * 50
                }, 15000); //bottom arrow key
                break;
        }
    }
    pressed = true;
}).keyup(function(){
    $('p').stop();
    pressed = false;
});

</script>
<style>
body {
    background-color: black;
}
div#life1 {
    width: 25px;
    height: 25px;
    background-image: url("life.png");
}
div#life2 {
    width: 25px;
    height: 25px;
    background-image: url("life.png");
}
div#life3 {
    width: 25px;
    height: 25px;
    background-image: url("life.png");
}
p#pacman {
	width: 50px;
	height: 50px;
	position: absolute;
    background-image: url("pacman-left.png");
}
div#blinky {
    width:30px;
    height:30px;
    position:fixed;
    background-image: url("blinky.jpg");
}
div#inky {
    width:30px;
    height:30px;
    position:fixed;
    background-image: url("inky.jpg");
}
div#pinky {
    width:30px;
    height:30px;
    position:fixed;
    background-image: url("pinky.jpg");
}
div#clyde {
    width:30px;
    height:30px;
    position:fixed;
    background-image: url("clyde.jpg");
}
div#cherry {
    width:56px;
    height:56px;
    position:fixed;
    background-image: url("cherry.png");
}
</style>
<body>
<table style='color: white'>
    <tr>
        <td><div id="life1"></div></td>
        <td><div id="life2"></div></td>
        <td><div id="life3"></div></td>
    </tr>
</table>
	<div id='blinky'></div>
    <div id='inky'></div>
    <div id='pinky'></div>
    <div id='clyde'></div>
	<p id="pacman"></p>
    <div id='cherry'></div>

</body>

回答1:


i dont see any atempt in your code at collision detection but it is very simple especally in 2D.

lets say you have 2 objects - A (pacman) and B (cherry)

if you want to know if they have collided then you need to do a point to point calculation.

Imagine drawing a circle round both that just fits, get the radius of the circle and then checking if distance between the two centre points of the circles is less than the circle radius. like so:-

float x, y;
float CircleRadius = 2.0f;
x = SmallModel->GetX() - LargeModel->GetX();    
y = SmallModel->GetY() - LargeModel->GetY();    


float collisionDist = sqrt( x*x + y*y);  

if (collisionDist < sphereRadius)
{
// Collision occurred…
}

its as easy as that




回答2:


You have an if condition somewhere in your code wherein you are doing console.log('hi') and I think this is your collision detection attempt though it's not clear. Here's a javascript solution for radius detection, similar to Rob85's approach:

function isColliding(pacman, bonusItem) {
    var dx = pacman.x - bonusItem.x;
    var dy = pacman.y - bonusItem.y;
    var rr = pacman.radius + bonusItem.radius;
    if (dx * dx + dy * dy < rr * rr)
        return true;
    else
        return false;
}

This assumes you give a 'hitbox' to your pacman and bonusItem objects in addition to the x and y coordinate properties. The idea is you test two circles colliding.

var pacman = {
    speed: 256,
    x: 0,
    y: 0,
    height: 50,
    width: 50,
    radius: (height + width) / 4 //roughly half the average hw
};

var cherry = {
    x: 100,
    y: 100,
    height: 56,
    width: 56,
    radius: (height + width) / 4; //roughly half the average hw
};

I think circle-circle collision is simplest, so a good place to start and certainly adequate for Pacman and all of its complexity.

There's thorough coverage on circle-square collision in this post: Circle-Rectangle collision detection (intersection)

Moreover, you can consider doing a check of every pixel in your sprites. I never tried it, but this post looks helpful: Can someone explain per-pixel collision detection?

You may also consider using square-square collision detection. In general, here's a great article by Mozilla Developer Network: 2d collision detection



来源:https://stackoverflow.com/questions/31595224/my-collision-detection-isnt-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!