zoukankan      html  css  js  c++  java
  • 一个简单的触壁反弹(js原生)

    <!DOCTYPE html>
    
    <html>
    
    <head>
    
    <meta charset="UTF-8">
    
    <title></title>
    
    <style type="text/css">
    
    *{padding: 0;margin: 0;}
    
    #box{width: 500px;height: 350px;border:1px solid #ccc;margin: 20px auto 0;position: relative;}
    
    #ball{width: 50px;height: 50px;background: red;position: absolute;top:0;left: 0;}
    
    #btn{width: 50px;height: 50px;cursor: pointer;background: green;}
    
    </style>
    
    </head>
    
    <body>
    
    <div id="box">
    
      <div id="ball">
    
      </div>
    
    </div>
    
    <div id="btn">
    
     
    
    </div>
    
    </body>
    
    </html>
    
    <script type="text/javascript">
    
    var box=document.getElementById("box");
    
    var ball=document.getElementById("ball");
    
    var btn=document.getElementById("btn");
    
    var speedX=10;//横向的移动速度
    
    var speedY=10;//横向的移动速度
    
    //点击更改ball的速度
    
    btn.onclick=function(){
    
    speedX=parseInt(Math.random()*4+1)+2;
    
    speedY=parseInt(Math.random()*4+1)+2;
    
    }
    
    setInterval(function(){
    
    ball.style.left=ball.offsetLeft+speedX+"px";
    
    ball.style.top=ball.offsetTop+speedY+"px";
    
    //判断ball的位置 触壁speed取反
    
    if(ball.offsetLeft>=box.clientWidth-ball.offsetWidth||ball.offsetLeft<=0){
    
    speedX*=-1;
    
    }
    
    if(ball.offsetTop>=box.clientHeight-ball.offsetHeight||ball.offsetTop<=0){
    
    speedY*=-1;
    
    }
    
    },30)
    
    </script>

    主要运用的知识点:原生的js碰撞检测

  • 相关阅读:
    WPF画辐射图
    WPF 获取表格里面的内容
    C# 动态生成Html地图文件
    C#如何关闭指定进程
    oracle EM 打不开 503 |OracleDBConsoleorcl 启动不了
    oracle windows 下修复无监听错误-12541/12514
    Oracle 命令汇总
    oracle 函数 bitand 与 decode
    一.Git 初步扫盲
    修改字段类型
  • 原文地址:https://www.cnblogs.com/jwhgz/p/6061035.html
Copyright © 2011-2022 走看看