javascript - 如何仅在 JS/jQuery 中处理冲突?

标签 javascript jquery html css

我很难用 js(仅 jQuery)为我的游戏制作碰撞。我希望 Angular 色能够从一个平台跳到另一个平台。另外,我想要一个 console.log('hit');当其中一个 Angular 色用一枪击中另一个 Angular 色时。最近两天我一直在努力。我卡住了。

这是我的代码:

setInterval(bougerPersonnages, 8); //Vitesse de déplacement.
var touche = {}
var batmanp = document.getElementById('batman');
var jumping = false;
var jumpingChomel = false;
var barpos = $("#batman");
var browserHeight = parseInt(document.documentElement.clientHeight);
var iHeight = window.innerHeight;




var batmanPosX = $("#batman").offset().left;
var batmanPosY = $("#batman").offset().top;
var batmanWidth = $("#batman").width();
var batmanHeigth = $("#batman").height();

var ballePosX = $('#arrow1').offset().left;
var ballePosY = $('#arrow1').offset().top;
var balleWidth = $('#arrow1').width();
var balleHeight = $('#arrow1').height();


$(document).keydown(function(e) { //Fonctionne
    touche[e.keyCode] = true;
});

$(document).keyup(function(e) { //Fonctionne
    delete touche[e.keyCode];
});


function bougerPersonnages() {

    for (var direction in touche) {
        if (direction == 37) { //Fonctionne
        	batman.className = 'dirGauche';
        	$("#batman").css('left','-=5px');
        }

        if (direction == 81) { //Fonctionne
        	chomel.className = 'dirGauche';
            $("#chomel").css('left', '-=5');	
        }
     
        if (direction == 39) { //Fonctionne
        	batman.className = 'dirDroite';
            $("#batman").css('left', '+=5');      		
        }

        if (direction == 68) { //Fonctionne
        	chomel.className = 'dirDroite';
            $("#chomel").css('left', '+=5');      		
        }

        if (direction == 38) { //Fonctionne
		    if (!jumping) {
			    jumping = true;
			    $("#batman").animate({ bottom: 300 +"px" }, 300);
			    $("#batman").animate({ bottom: 10 + "px" }, 300);
			    setTimeout(land, 650);
 			}
 		}

 		if (direction == 90) { //Fonctionne
		 	if (!jumpingChomel) {
			    jumpingChomel = true;
			    $("#chomel").animate({ bottom: 300 +"px" }, 300);
			    $("#chomel").animate({ bottom: 10 + "px" }, 300);
			    setTimeout(landChomel, 650);			   
     		}
     	}


	}

		
}




//Fonctionne
function land() {
    
  jumping = false;

}

function landChomel() {
    
  jumpingChomel = false;

}
//Fonctionne
document.addEventListener('keydown', function(e) { // Déclenche la fonction fire
	
	switch (e.keyCode) {

        case 76:
        console.log('ok');
            fire_batman();
        break;
        case 32:
        console.log('ok');
            fire_chomel();
        break;     
    }

});

function fire_chomel() { //Fonctionne

	var posTop = parseInt($(chomel).offset().top);
    var posLeft = parseInt($(chomel).offset().left);
	var bullets = $('#arrow1');
	var bulletElement = $('<div class="arrow1" style="top: '+ (posTop + 50) +'px; left: '+ posLeft +'px"></div>');

    bullets.append(bulletElement);

    if (chomel.className == 'dirGauche') {
    	var options = {left: browserHeight * -15};
    }
    else {
    	var options = {left: browserHeight * 15};
    }

	bulletElement.animate(options, 0.5, "linear");
}

function fire_batman() { //Fonctionne

	var posTop = parseInt($(batman).offset().top);
    var posLeft = parseInt($(batman).offset().left);
	var bullets = $('#arrow1');
	var bulletElement = $('<div class="arrow1" style="top: '+ (posTop + 50) +'px; left: '+ posLeft +'px"></div>');

    bullets.append(bulletElement);

    if (batman.className == 'dirGauche') {
    	var options = {left: browserHeight * -15};
    }
    else {
    	var options = {left: browserHeight * 15};
    }

	bulletElement.animate(options, 0.5, "linear");
	var rect1 = {x: batmanPosX, y: batmanPosY, width: batmanWidth, height: batmanHeigth}
var rect2 = {x: ballePosX, y: ballePosY, width: balleWidth, height: balleHeight}

if (rect1.x < rect2.x + rect2.width &&
   rect1.x + rect1.width > rect2.x &&
   rect1.y < rect2.y + rect2.height &&
   rect1.height + rect1.y > rect2.y) {
    // collision detected!
    console.log('TOUCHER FDP')
}

// filling in the values =>

if (5 < 30 &&
    55 > 20 &&
    5 < 20 &&
    55 > 10) {
    // collision detected!
}
}
body {
	padding: 0;
	margin: 0;
	background: url('http://image.noelshack.com/fichiers/2015/16/1429119282-bg.png');
	background-color: #B4381F;
	background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: 100%;
    background-position: 50% 30%; 
	overflow: hidden;
}


#batman{
	background-image:url('http://image.noelshack.com/fichiers/2015/16/1429119282-batman.png');
	width:90px;
	height:90px;
	display:block;
	background-repeat: no-repeat;
	position:absolute;
}

#chomel{
	background-image:url('http://image.noelshack.com/fichiers/2015/16/1429119282-chomel.png');
	width:90px;
	height:90px;
	display:block;
	background-repeat: no-repeat;
	position:absolute;
}

.dirDroite{
	background-position: -95px 0px;
}

.dirGauche{
	background-position: 0px 0px;
}

#fullbody {
	margin: auto;
	width: 100%;
	height: 100%;
}

#floor {
	position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
	background: url("http://image.noelshack.com/fichiers/2015/16/1429119282-thefloor.png");
	background-repeat: repeat-x;
	background-size: 100% 100%;
	height: 126px;
	
}

#base {
	position: absolute;
    right: 0;
    bottom: 100px;
    left: 0;
    z-index: 200;
	margin: auto;
	background: url('http://image.noelshack.com/fichiers/2015/16/1429119282-platform5.png');
	background-size: cover;
	width: 600px;
	height: 30px;
}



#perspectiveGauche{
	margin-top : 22vh;
	-webkit-perspective: 4vh;
    perspective: 4vh;
    position: absolute;
    width: 45vw;
    perspective-origin: 50% 0%;
}

#rectangleHautGaucheH{
	margin-left: 13.22vh;
	width: 28.87vw;
	height: 2vh;
	background-color: #854305;
    -webkit-transform: rotateX(2deg);
    transform: rotateX(2deg);
}

#rectangleBasGaucheH{
	width: 29.1vw;
	margin-left: 13vh;
	height: 3vh;
	background-color: #663303; 
}

#perspectiveGaucheBasse{
	margin-top : 22vh;
	-webkit-perspective: 0.1vh;
    perspective: 0.1vw;
    position: absolute;
    width: 45vw;
    perspective-origin: 50% 0%;
}

#rectangleHautGaucheB{
	margin-top: 38vh;
	margin-left: 28vh;
	width: 15vw;
	height: 0.25vh;
	background-color: #854305;
    -webkit-transform: rotateX(2deg);
    transform: rotateX(2deg);
}

#rectangleBasGaucheB{
	margin-top: 0.6vh;
	width: 15.3vw;
	margin-left: 27.75vh;
	height: 3vh;
	background-color: #663303; 
}

#perspectiveDroite{
	-webkit-perspective: 4vh;
    perspective: 4wh;
    position: absolute;
    width: 39.6vw;
    height: 2vh;
    margin-top: 22vh;
    perspective-origin: 200% 0%;
}

#rectangleHautDroitH{
	margin-left: 125vh;
	width: 28.7vw;
	height: 2vh;
	background-color: #854305;
    -webkit-transform: rotateX(2deg);
    transform: rotateX(2deg);
}

#rectangleBasDroitH{
	width: 28.9vw;
	margin-left: 124.8vh;
	height: 3vh;
	background-color: #663303; 
}

#rectangleHautDroiteB{
	margin-top: 32vh;
	margin-left: 133vh;
	width: 22vw;
	height: 2vh;
	background-color: #854305;
    -webkit-transform: rotateX(2deg);
    transform: rotateX(2deg);
}

#rectangleBasDroiteB{
	margin-top: 0.2vh;
	width: 22.18vw;
	margin-left: 132.8vh;
	height: 3vh;
	background-color: #663303; 
}

#perspectiveMilieu{
	-webkit-perspective: 4vh;
    perspective: 4wh;
    position: absolute;
    width: 39.6vw;
    height: 2vh;
    margin-top: 22vh;
    perspective-origin: 130% 0%;
 
}

#rectangleHautMilieu{
	margin-top: 21vh;
	margin-left: 68.95vh;
	width: 34.5vw;
	height: 2vh;
	background-color: #854305;
    -webkit-transform: rotateX(2deg);
    transform: rotateX(2deg);
    
}

#rectangleBasMilieu{
	margin-top: 0.1vh;
	width: 34.77vw;
	margin-left: 68.7vh;
	height: 3vh;
	background-color: #663303; 
}

.arrow1 {
	position: absolute;
	z-index: 3;
	transition-duration: 3s;
	width: 50px;
	height: 11px;
	background: url('http://image.noelshack.com/fichiers/2015/16/1429119282-bullet.png') 43px 19px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>LEVEL 1</title>
	<link rel="stylesheet" type="text/css" href="style.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
	
</head>
<body>


<div id="fullbody">

	<div id="perspectiveGauche">
		<div id="rectangleHautGaucheH"></div>
		<div id="rectangleBasGaucheH"></div>
	</div>

	<div id="perspectiveGaucheBasse">
		<div id="rectangleHautGaucheB"></div>
		<div id="rectangleBasGaucheB"></div>
	</div>

		<div id="perspectiveDroite">
			<div id="rectangleHautDroitH"></div>
			<div id="rectangleBasDroitH"></div>
			<div id="rectangleHautDroiteB"></div>
			<div id="rectangleBasDroiteB"></div>
		</div>

		<div id="perspectiveMilieu">
			<div id="rectangleHautMilieu"></div>
			<div id="rectangleBasMilieu"></div>
		</div>

	
		<div id="base"></div>
		<div id="arrow1"></div>
		<div id="floor"></div>
		<span style="margin-left:50px;" id="result">false</span>

	<div id="batman" name="batman" class="dirGauche" style="left: 1100px; bottom: 580px;"></div>
	<div id="chomel" name="chomel" class="dirGauche" style="left: 900px; bottom: 580px;"></div>

</div>
	
	<script src="scripts/script.js" ></script>

同时加入一个 jsfiddle:https://jsfiddle.net/b6hq4xqr/

预先感谢您的回复。 干杯!

最佳答案

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>LEVEL 1</title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    </head>
    <body>


        <div id="fullbody">

            <div id="perspectiveGauche">
                <div id="rectangleHautGaucheH"></div>
                <div id="rectangleBasGaucheH" class="collidableRectangle"></div>
            </div>

            <div id="perspectiveGaucheBasse">
                <div id="rectangleHautGaucheB"></div>
                <div id="rectangleBasGaucheB" class="collidableRectangle"></div>
            </div>

            <div id="perspectiveDroite">
                <div id="rectangleHautDroitH"></div>
                <div id="rectangleBasDroitH" class="collidableRectangle"></div>
                <div id="rectangleHautDroiteB"></div>
                <div id="rectangleBasDroiteB" class="collidableRectangle"></div>
            </div>

            <div id="perspectiveMilieu">
                <div id="rectangleHautMilieu"></div>
                <div id="rectangleBasMilieu" class="collidableRectangle"></div>
            </div>


            <div id="base"></div>
            <div id="arrow1"></div>
            <div id="floor"></div>
            <span style="margin-left:50px;" id="result">false</span>

            <div id="batman" class="dirGauche" style="left: 1100px; bottom: 580px;"></div>
            <div id="chomel" class="dirGauche" style="left: 900px; bottom: 580px;"></div>

        </div>

        <script src="javascript.js" ></script>
    </body>
</html>

打破

function bougerPersonnages() {

    for (var direction in touche) {
        if (direction == 37) { //Fonctionne
            batman.className = 'dirGauche';
            $("#batman").css('left', '-=5px');
        } else if (direction == 81) { //Fonctionne
            chomel.className = 'dirGauche';
            $("#chomel").css('left', '-=5');
        } else if (direction == 39) { //Fonctionne
            batman.className = 'dirDroite';
            $("#batman").css('left', '+=5');
        } else if (direction == 68) { //Fonctionne
            chomel.className = 'dirDroite';
            $("#chomel").css('left', '+=5');
        } else if (direction == 38) { //Fonctionne
            if (!jumping) {
                jumping = true;
                $("#batman").animate({bottom: 300 + "px"}, 300);
                $("#batman").animate({bottom: 10 + "px"}, 300);
                setTimeout(land, 650);
            }
        }
        else if (direction == 90) { //Fonctionne
            if (!jumpingChomel) {
                jumpingChomel = true;
                $("#chomel").animate({bottom: 300 + "px"}, 300);
                $("#chomel").animate({bottom: 10 + "px"}, 300);
                setTimeout(landChomel, 650);
            }
        }
    }

    var batmanRect = getRectangle($("#batman"));
    $(".arrow1").each(function () {
        var rect = getRectangle($(this));
        if (intersectingRectangles(batmanRect, rect)) {
            console.log("batman has been shot!");
        }
    });

    $(".collidableRectangle").each(function () {
        var rect = getRectangle($(this));
        if (intersectingRectangles(batmanRect, rect)) {
            console.log("batman has hit a platform!");
        }
    });
}

function fire_chomel() { //Fonctionne

    var posTop = parseInt($(chomel).offset().top);
    var posLeft = parseInt($(chomel).offset().left);
    var bullets = $('#arrow1');
    var bulletElement = $('<div class="arrow1" style="top: ' + (posTop + 50) + 'px; left: ' + posLeft + 'px"></div>');

    bullets.append(bulletElement);

    if (chomel.className == 'dirGauche') {
        var options = {left: browserHeight * -15};
    }
    else {
        var options = {left: browserHeight * 15};
    }

    bulletElement.animate(options, 2000, "linear", function () {
        $(this).remove();
    });
}


function intersectingRectangles(r1, r2) {
    return !(r2.left > r1.right ||
            r2.right < r1.left ||
            r2.top > r1.bottom ||
            r2.bottom < r1.top);
}

function getRectangle(figure) {
    var rect = {};
    rect.left = figure.offset().left;
    rect.top = figure.offset().top;
    rect.right = rect.left + figure.width();
    rect.bottom = rect.top + figure.height();
    return rect;
}

我也删除了

.arrow1 {
    transition-duration: 3s;
}

您面临的大多数问题都是由于您(滥用)使用全局变量造成的。每个有经验的程序员都会告诉你要谨慎使用全局变量,甚至尽可能避免使用。这是有充分理由的。

这只实现了第一个fire函数,其他的是模拟的,你应该可以自己做。 碰撞现在记录到控制台。 我试图通过对您的代码进行最少的更改来做到这一点。我建议您在继续之前考虑尽量减少对全局变量的使用。

关于javascript - 如何仅在 JS/jQuery 中处理冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29657031/

相关文章:

javascript - jQuery .animate() 导致输入不稳定

javascript - jQuery 周历 : cannot call method 'getTime' of undefined

java - getActionCommand在代码中不起作用(观看教程系列)

c# - 无法在 Bootstrap 的 select2 插件中设置选定值

javascript - 使用 JavaScript 中的 mailchimp API 显示终端中的所有项目

javascript - 从 localStorage 获取 getElementByID

javascript - 主干滚动事件未触发

jQuery:URL 不带 'page jump' 的选项卡

javascript - 获取通过 javascript 创建的输入文本的值

javascript - div类更改时更改背景颜色?