javascript - 如何使用 javascript 在 div 上移动对象?

标签 javascript html

我正在尝试使用 div 创建一个游戏来创建背景,以便对象有一个可以移动的设定区域。对我来说,第一步是让墙在屏幕上向“汽车”对象移动。我试图通过识别它的 x 并改变它来做到这一点,但它不起作用。我认为这可能与我没有使用 Canvas 有关,但除非绝对需要,否则我宁愿不使用 Canvas 。这是我的代码:

<!DOCTYPE html>
<html>
  <head>
    <style>

      #grass {
        background-color: green;
        height: 100px;
        width: 750px;
      }

      #road {
        background-color: grey;
        height: 200px;
        width: 750px;
      }

      #ai {
        position: absolute;
        background-color: red;
        height: 50px;
        width: 100px;
        margin-top: 75px;
      } 

      #obstacle {
        background-color: blue;  
        height: 100px;
        width: 50px;
        float: right;
      }

      .sensor {
        position: relative;
        background-color: white;
        width: 50px;
        height: 50px;
        text-align: center;
        opacity: 0.5;
      }

      #sensor1 {
        top: 50px;
        left: 50px;
      }

      #sensor2 {
        top: -50px;
        left: 100px;
        width: 300px;;
      }

      #sensor3 {
        top: -150px;
        left: 50px;
      }

    </style>
  </head>
  <body>
    <div id="scene">
      <div id="grass">
      </div>
      <div id="road">
        <div id="ai">
          <div id="sensor1" class="sensor">1</div>
          <div id="sensor2" class="sensor">2</div>
          <div id="sensor3" class="sensor">3</div>
        </div>
        <div id="obstacle">
        </div>
      </div>
      <div id="grass">
      </div>
    </div>
    <br />
    <br />
    <button onclick="moveWall()">Run</button>
    <script>
      function moveWall(x) {

      getWallx = document.getElementById("obstacle").x;
      this.speedX = 0;

       if(getWallx <= 0) {
         document.getElementById("obstacle").style.left = null;
         document.getElementById("obstacle").style.right = "0px";
       } else {
          getWallx -= this.speedX
          document.getElementById("obstacle").style.left = getWallx+'px';

        }
      }
    </script>
  </body>
</html>

最佳答案

这是另一个与您的问题类似的问题。 Moving Div Box using javascript ,如果你必须在游戏中使用 div,这应该是一个很好的起点

但我建议使用 Canvas ,因为它有更好的移动 API 等。

尝试从片段中进行此操作。 w3school

var myGamePiece;
var myObstacles = [];
var myScore;

function startGame() {
    myGamePiece = new component(30, 30, "red", 10, 120);
    myGamePiece.gravity = 0.05;
    myScore = new component("30px", "Consolas", "black", 280, 40, "text");
    myGameArea.start();
}

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.frameNo = 0;
        this.interval = setInterval(updateGameArea, 20);
        },
    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

function component(width, height, color, x, y, type) {
    this.type = type;
    this.score = 0;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;    
    this.x = x;
    this.y = y;
    this.gravity = 0;
    this.gravitySpeed = 0;
    this.update = function() {
        ctx = myGameArea.context;
        if (this.type == "text") {
            ctx.font = this.width + " " + this.height;
            ctx.fillStyle = color;
            ctx.fillText(this.text, this.x, this.y);
        } else {
            ctx.fillStyle = color;
            ctx.fillRect(this.x, this.y, this.width, this.height);
        }
    }
    this.newPos = function() {
        this.gravitySpeed += this.gravity;
        this.x += this.speedX;
        this.y += this.speedY + this.gravitySpeed;
        this.hitBottom();
    }
    this.hitBottom = function() {
        var rockbottom = myGameArea.canvas.height - this.height;
        if (this.y > rockbottom) {
            this.y = rockbottom;
            this.gravitySpeed = 0;
        }
    }
    this.crashWith = function(otherobj) {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);
        var crash = true;
        if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
            crash = false;
        }
        return crash;
    }
}

function updateGameArea() {
    var x, height, gap, minHeight, maxHeight, minGap, maxGap;
    for (i = 0; i < myObstacles.length; i += 1) {
        if (myGamePiece.crashWith(myObstacles[i])) {
            return;
        } 
    }
    myGameArea.clear();
    myGameArea.frameNo += 1;
    if (myGameArea.frameNo == 1 || everyinterval(150)) {
        x = myGameArea.canvas.width;
        minHeight = 20;
        maxHeight = 200;
        height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
        minGap = 50;
        maxGap = 200;
        gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
        myObstacles.push(new component(10, height, "green", x, 0));
        myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
    }
    for (i = 0; i < myObstacles.length; i += 1) {
        myObstacles[i].x += -1;
        myObstacles[i].update();
    }
    myScore.text="SCORE: " + myGameArea.frameNo;
    myScore.update();
    myGamePiece.newPos();
    myGamePiece.update();
}

function everyinterval(n) {
    if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
    return false;
}

function accelerate(n) {
    myGamePiece.gravity = n;
}

startGame()
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p>Use the ACCELERATE button to stay in the air</p>
<p>How long can you stay alive?</p>

关于javascript - 如何使用 javascript 在 div 上移动对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60422033/

相关文章:

javascript - 在前端下载ANSI zip文件,由C#后端生成

javascript - IndexedDB - ObjectStores vs 多个数据库 vs 索引?

javascript - 从 html 表单到 javascript

javascript - 使用本地日期设置和获取 HTMLInputElement.valueAsDate 的正确方法是什么?

java - java/jsp中的telneting ip/port

javascript - Angular 仅显示一次表格标题,如果没有数据则隐藏标题

javascript - 如何使用jquery将td集中在表中?

javascript - 使用 PhantomJS 运行 TypeScript 文件

javascript - 滑动图像缓动

html - 如何在 HTML 中正确使用 lang