2 JS / jQuery脚本不能以相同的方式工作,无法找到原因

时间:2015-04-16 18:35:19

标签: javascript jquery html css html5

我目前正在开发一个只有js / jQuery的平台小游戏。我有两个脚本,一个我正在检测平台,让角色继续下去而不是下降。一个有一个很好的平滑跳跃。我想合并它们,但出于某种原因我不能。当我尝试这样做时,我的角色不再动了......

所以,如果你对我如何做到这一点有任何想法,那真的很棒。

这是我的剧本,希望你们能找到我不能做的...

//------------------ VIE -------------------------------
function CLife(iPlayerNum) {
  // iPlayerNum est egal a 1 ou 2
  this.propNumPlayer = iPlayerNum;

  // Image pour la vie
  this.ImgHeight = 30;
  this.ImgWidth  = 30;
  this.ImgName   = 'heart.png';

  // Nb de vie
  this.NbLife = 3;
}

CLife.prototype.Creer = function()
{
  // Créer la ligne d'etoiles
  var parent = document.getElementById("vie");
  var child = document.createElement('div'+this.propNumPlayer);
  child.setAttribute('id','div_life'+this.propNumPlayer);

  if(this.propNumPlayer == 1)
  {
    // Joueur 1 a gauche
    child.setAttribute('style','float:left; height:'+this.ImgHeight+'px; width: '+this.NbLife*this.ImgWidth+'px;');
  }
  else
  {
    // Joueur 2 a droite
    child.setAttribute('style','float:right; height:'+this.ImgHeight+'px; width: '+this.NbLife*this.ImgWidth+'px;');
  }
  parent.appendChild(child);

  // Ajouter les coeurs
  parent = document.getElementById('div_life'+this.propNumPlayer);
  for(var i=0; i < this.NbLife; i++)
  {
    child = document.createElement('img');
    child.setAttribute('id','img_'+(i+1)+'_'+this.propNumPlayer);
    child.setAttribute('src','img/'+this.ImgName);
    child.setAttribute('width','30 px');
    child.setAttribute('height','30 px');
    parent.appendChild(child);
  }
}

// YJoueur : ordonnée du joueur + la hauteur de l'image associee au joueur
CLife.prototype.TestFinVie = function(iYJoueur)
{
  var valret = false;

  console.log('Joueur  : ' + iYJoueur);
  console.log('Fenetre : ' + $(window).height());

  //if(iYJoueur <= 10/*>= $(window).height()*/)
  if(iYJoueur >= $(window).height())
  {
    star = document.getElementById('img_'+this.NbLife+'_'+this.propNumPlayer);
    if (star != null)
    {
    	star.style.display = 'none';
    	this.NbLife = this.NbLife - 1;
    	valret = true;
    }
  }

  return valret;
}
//------------------ VIE -------------------------------


setInterval(bougerPersonnages, 9); //Vitesse de déplacement.
var touche = {}
var jumping = false;
var jumpingChomel = false;
var browserHeight = parseInt(document.documentElement.clientHeight);
var batmanHurt = 0;

var batmanPosX = $("#batman").offset().left;
var chomelPosX = $("#chomel").offset().left;

var tombe = false;

var life1 = new CLife(2);
var life2 = new CLife(1);

life1.Creer();
life2.Creer();


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

$(document).keyup(function(e) { //Fonctionne
    delete touche[e.keyCode];
});
//------INTEGRATION COLLISION DE PLATEFORME----------
//
var platforms = [];
var currentPlatform = null;
var $batman = $('#batman');



function bougerPersonnages() {

		if(tombe == true)
		{
			// tester	la fin de vie des personnages
			var YPos = parseInt($("#batman").offset().top) + parseInt($("#batman").height()) + 10; // car le personnage tombe au plus bas à 10 px du bas de l'écran

			if (life1.TestFinVie(YPos) == true)
			{
  			//reinitialiser le personnage
        document.getElementById('batman').setAttribute('class','dirGauche');
        document.getElementById('batman').setAttribute('style','left: 1100px; bottom: 580px;');
			}

			YPos = parseInt($("#chomel").offset().top) + parseInt($("#chomel").height()) + 10; // car le personnage tombe au plus bas à 10 px du bas de l'écran
			if (life2.TestFinVie(YPos) == true)
			{
  			//reinitialiser le personnage
        document.getElementById('chomel').setAttribute('class','dirGauche');
        document.getElementById('chomel').setAttribute('style','left: 900px; bottom: 580px;');
			}
			tombe = false;
		}

    var top = $batman.offset().top;
    var left = $batman.offset().left;
    var newTop = top;
    var newLeft = left;

    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', '-=5px');
        } else if (direction == 39) { //Fonctionne
            batman.className = 'dirDroite';
            $("#batman").css('left', '+=5px');
        } else if (direction == 68) { //Fonctionne
            chomel.className = 'dirDroite';
            $("#chomel").css('left', '+=5px');
        } 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);
                setTimeout(function() {$("#chomel").animate({bottom: 10 + "px"}, 300) }, 350);
                setTimeout(landChomel, 650);
            }
        }
    }

    var batmanRect = getRectangle($("#batman"));
    var chomelRect = getRectangle($("#chomel"));
    $(".arrow1").each(function () {
        var rect = getRectangle($(this));
        if (intersectingRectangles(batmanRect, rect)) {
          var batmanPosX = $("#batman").offset().left;
      var chomelPosX = $("#chomel").offset().left;
            console.log("batman has been shot!");
            console.log("batman:" + batmanPosX);
            console.log("chomel:" + chomelPosX);
            console.log($(this).attr('data-arrow'));
            
            if (batmanPosX < chomelPosX && $(this).attr('data-arrow') == "chomelShoot") {
              $("#batman").animate({left: "-=50px"}, 40);
            }
            else if ($(this).attr('data-arrow') == "chomelShoot"){
              $("#batman").animate({left: "+=50px"}, 40);
            }            
        } else if (intersectingRectangles(chomelRect, rect)) {
          var batmanPosX = $("#batman").offset().left;
          var chomelPosX = $("#chomel").offset().left;
            console.log("batman has been shot!");
            console.log("batman:" + batmanPosX);
            console.log("chomel:" + chomelPosX);
            console.log($(this).attr('data-arrow'));
            
            if (chomelPosX < batmanPosX && $(this).attr('data-arrow') == "batmanShoot") {
              $("#chomel").animate({left: "-=50px"}, 40);
            }
            else if ($(this).attr('data-arrow') == "batmanShoot"){
              $("#chomel").animate({left: "+=50px"}, 40);
            }

            
        }
    });

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


function land() {

  jumping = false;
	tombe = true;
}

function landChomel() {

  jumpingChomel = false;
	tombe = true;
}




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

        case 76:
            fire_batman();
        break;
        case 32:
            fire_chomel();
        break;     
    }

});

function fire_chomel() { //Fonctionne

    var posTop = parseInt($(chomel).offset().top);
    if (chomel.className == 'dirGauche') {
      var posLeft = parseInt($(chomel).offset().left) - 30;
    }
    else {
        var posLeft = parseInt($(chomel).offset().left) + 120;
    }
    var bullets = $('#arrow1');
    var bulletElement = $('<div class="arrow1" data-arrow="chomelShoot" style="top: ' + (posTop + 14) + 'px; left: ' + posLeft + 'px"></div>');

    bullets.append(bulletElement);

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

    ok = new Audio('sound/pistolet.mp3');
    ok.play();
    bulletElement.animate(options, 2000, "linear", function () {
        $(this).remove();
    });
}

function fire_batman() { //Fonctionne

    var posTop = parseInt($(batman).offset().top) - 27;

    if (batman.className == 'dirGauche') {
      var posLeft = parseInt($(batman).offset().left) - 51;
    }
    else {
        var posLeft = parseInt($(batman).offset().left) + 106;
    }

    var bullets = $('#arrow1');
    var bulletElement = $('<div class="arrow1" data-arrow="batmanShoot" 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};
    }

    ok = new Audio('sound/pistolet.mp3');
  ok.play();
    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;
}
body {
	padding: 0;
	margin: 0;
	background: url('http://image.noelshack.com/fichiers/2015/16/1429209179-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/1429209179-batman.png');
	width:119px;
	height:87px;
	display:block;
	background-repeat: no-repeat;
	position:absolute;
}

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

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

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

#hautGauche{
	margin-top: 25vh;
	position: fixed;
	width: 15vw;
	margin-left: 30vh;
	height: 3vh;
	background-color: #663303;
	z-index: 1; 
}

#hautDroite{
	margin-top: 25vh;
	position: fixed;
	width: 15vw;
	margin-left: 125vh;
	height: 3vh;
	background-color: #663303; 
	z-index: 2;
}

#milieu{
	margin-top: 45vh;
	position: fixed;
	width: 50vw;
	margin-left: 45vh;
	height: 3vh;
	background-color: #663303; 
	z-index: 3;
}

#basGauche{
	margin-top: 65vh;
	position: fixed;
	width: 25vw;
	margin-left: 27.75vh;
	height: 3vh;
	background-color: #663303; 
	z-index: 4;
}


#basDroite{
	margin-top: 65vh;
	position: fixed;
	width: 22.18vw;
	margin-left: 132.8vh;
	height: 3vh;
	background-color: #663303; 
	z-index: 5;
}

#base{
	margin-top: 85vh;
	position: fixed;
	width: 49.77vw;
	margin-left: 50.7vh;
	height: 3vh;
	background-color: #663303; 
	z-index: 6;
}

#invisible {
	position: fixed;
    right: 0;
    bottom: 0px;
    left: 0;
    z-index: 200;
	margin: auto;
	background-color: black;
	width: 100%;
	height: 30px;
	opacity: 0;
	z-index: 7;
}
.arrow1 {
	position: absolute;
	z-index: 3;
	width: 50px;
	height: 11px;
	background: url('http://image.noelshack.com/fichiers/2015/16/1429209179-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 data-platform="true" id="hautGauche" class="collidableRectangle"></div>

                <div data-platform="true" id="hautDroite" class="collidableRectangle"></div>

                <div data-platform="true" id="milieu" class="collidableRectangle"></div>

                <div data-platform="true" id="basGauche" class="collidableRectangle"></div>

                <div data-platform="true" id="basDroite" class="collidableRectangle"></div>

                <div data-platform="true" id="base" class="collidableRectangle"></div>

                <div data-platform="true" id="invisible"></div>


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

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

            <div id="vie">
            </div>
        </div>

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

上面的代码是具有工作跳转的代码,这里是具有工作平台的代码:

var platforms = [];
var currentPlatform = null;
var $roger = $('#batman');

$(document).on('keydown', function (e) {
    var top = $roger.offset().top;
    var left = $roger.offset().left;
    var newTop = top;
    var newLeft = left;
 
 
    switch (e.keyCode) {
        case 32:
            newTop = top - 400;
            $roger.css("top", newTop);
 
            setTimeout(function () {
                $roger.css("top", top);
            }, 100);
            break;
 
        case 37:
            newLeft = left - 50;
            $roger.css({left: newLeft});
            break;
 
        case 39:
            newLeft = left + 50;
            $roger.css({left: newLeft});
            break;
    }
});
 
 
setInterval(function () {
    verifyPlatform();
}, 50);
 
 
$('[data-platform="true"]').each(function () {
    var $element = $(this);
    var x = $element.offset().left;
    var y = $element.offset().top;
    var xw = x + $element.width();
    var yh = y + $element.height();
 
    platforms.push({
        element: $element,
        x: x,
        y: y,
        xw: xw,
        yh: yh
    });
});
 
 
function getPlatformAvailable(platforms) {
    var persoX = $roger.offset().left;
    var persoYH = $roger.offset().top + $roger.height();
 
    for (platform in platforms) {
        var current = platforms[platform];
 
        if (
            ((persoX + 50) >= current.x && persoX <= current.xw) &&
            ((persoYH) <= current.y)
        ) {
            return current;
        }
    }
 
    return false;
}
 
 
function verifyPlatform() {
    var platformAvailable = getPlatformAvailable(platforms);
    var platformAvailableString = platformAvailable.x +":"+ platformAvailable.y;
 
    if (platformAvailable && platformAvailableString != currentPlatform) {
        currentPlatform = platformAvailableString;
        $roger.css('top', (platformAvailable.y - $roger.height()));
    } 
}

谢谢你,如果你能理解并帮助我,我一整天都在努力。 干杯!

1 个答案:

答案 0 :(得分:1)

我看到你绑定了同一个事件两次:

在第一个代码段中:

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

在第二个代码段中:

$(document).on('keydown', function (e) {
    var top = $roger.offset().top;
    var left = $roger.offset().left;
    var newTop = top;
    var newLeft = left;


    switch (e.keyCode) {
        case 32:
            newTop = top - 400;
            $roger.css("top", newTop);

            setTimeout(function () {
                $roger.css("top", top);
            }, 100);
            break;

        case 37:
            newLeft = left - 50;
            $roger.css({left: newLeft});
            break;

        case 39:
            newLeft = left + 50;
            $roger.css({left: newLeft});
            break;
    }
});

如果将两个代码合并在一起,则意味着这两个事件将发生冲突,并且两个代码中只有一个会起作用。

解决方案

将它们正确地合并在一起以解决它:

$(document).on('keydown', function (e) {
    touche[e.keyCode] = true;

    var top = $roger.offset().top;
    var left = $roger.offset().left;
    var newTop = top;
    var newLeft = left;


    switch (e.keyCode) {
        case 32:
            newTop = top - 400;
            $roger.css("top", newTop);

            setTimeout(function () {
                $roger.css("top", top);
            }, 100);
            break;

        case 37:
            newLeft = left - 50;
            $roger.css({left: newLeft});
            break;

        case 39:
            newLeft = left + 50;
            $roger.css({left: newLeft});
            break;
    }
});