>  기사  >  웹 프론트엔드  >  jQuery_jquery로 구현한 분자 운동 공 충돌 효과

jQuery_jquery로 구현한 분자 운동 공 충돌 효과

WBOY
WBOY원래의
2016-05-16 15:17:181848검색

이 글의 예시에서는 jQuery로 구현한 분자 운동 공 충돌 효과를 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 자세한 내용은 다음과 같습니다.

먼저 렌더링을 살펴보겠습니다. 공이 움직이기 때문에 스크린샷을 찍기가 어렵습니다. 여기서는 실제 효과를 보고 싶다면 경로의 대략적인 개요를 그려보겠습니다. 붙여넣고 직접 실행해 보세요.

공이 좀 작아요 ㅎㅎ 자세한 내용은 다루지 않았네요. 완벽하게 만들고 싶으시면 직접 처리하셔도 됩니다! 이것이 시뮬레이션의 이상적인 상태입니다. 그룹 내 분자의 마찰과 충돌 운동이 없습니다. 코드가 아직 정리되지 않았습니다. 관심 있는 분들은 객체지향 형태로 정리해보세요!

코드는 다음과 같습니다.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <script src="jquery-1.7.1.min.js" type="text/javascript"></script>
  <script type="text/javascript" >
    var dim_half_past_PI = dimAngle(Math.PI / 2); // Math.PI/2的约数
    var lastAngle = dimAngle(Math.PI/8); // 发射角度(0-dimAngle(Math.PI))
    var v = 120; //飞行速度【>0】
    var lastPosition = {}; // 最后一次碰撞坐标
    var lastTime = ""; // 最后一次碰撞时间
    var lastDirection = "top"; // 开始发射方向(top,bottom,left,right)
    var horizen = 1; // 水品方向的积数
    var vertical = 1; // 竖直方向的积数
    var box = {};
    function dimAngle(angle) {
      var tempAngle = angle + "";
      return parseFloat(tempAngle.substring(0, 6));
    }
    function getWillDirection(position, box) {
      var direction = lastDirection;
      if (position.x < box.left) {
        direction = "right";
      }
      if (position.x > box.right) { 
        direction = "left"
      }
      if (position.y < box.top) {
        direction = "bottom";
      }
      if (position.y > box.bottom) {
        direction = "top";
      }
      return direction;
    }
    function getScale(direction, angle) { 
      switch(direction){
        case "top":
          vertical = -1;
          if (angle < dim_half_past_PI) {
            horizen = 1;
          }
          if (angle > dim_half_past_PI) {
            horizen = -1;
          }
          if (angle == dim_half_past_PI) {
            horizen = 0;
          }
          break;
        case "left":
          horizen = -1;
          if (angle > dim_half_past_PI) {
            vertical = 1;
          }
          if (angle < dim_half_past_PI) {
            vertical = -1;
          }
          if (angle == dim_half_past_PI) {
            vertical = 0;
          }
          break;
        case "bottom":
          vertical = 1;
          if(angle > dim_half_past_PI) {
            horizen = 1;
          }
          if(angle < dim_half_past_PI) {
            horizen = -1;
          }
          if(angle == dim_half_past_PI) {
            horizen = 0;
          }
          break;
        case "right":
          horizen = 1;
          if (angle > dim_half_past_PI) {
            vertical = -1;
          }
          if (angle < dim_half_past_PI) {
            vertical = 1;
          }
          if (angle == dim_half_past_PI) {
            vertical = 0;
          }
          break;
      }
    }
    function getOutAngle(inAngle) {
      if (inAngle == dim_half_past_PI || inAngle == 0) {
        return inAngle;
      } else {
        return dim_half_past_PI - inAngle;
      }
    }
    function setPosition(obj, position) {
      obj.css({ "left": position.x +"px", "top": position.y +"px"});
    }
    function run(obj) {
      var vx = Math.cos(lastAngle) * v;
      var vy = Math.sin(lastAngle) * v;
      var runTime = (new Date().getTime() - lastTime) / 1000;
      getScale(lastDirection, lastAngle);
      var sx = vx * runTime * horizen;
      var sy = vy * runTime * vertical;
      var position = {
        x: lastPosition.x + sx,
        y: lastPosition.y + sy
      };
      setPosition(obj, position);
      var currentDirection = getWillDirection(position, box);
      console.log(currentDirection +":"+lastDirection+":"+vertical+":"+horizen+":"+lastAngle+":"+dim_half_past_PI);
      // 如果没有发生碰撞
      if (currentDirection != lastDirection) {
        // 如果发生了碰撞
        lastDirection = currentDirection;
        lastPosition = position;
        lastTime = new Date().getTime();
        lastAngle = getOutAngle(lastAngle);
      }
      setTimeout(function () {
        run(obj);
      }, 30);
    }
    $(document).ready(function () {
      var boxer = $("#box");
      var x = parseInt(boxer.offset().left);
      var y = parseInt(boxer.offset().top);
      box = {
        left: x,
        top: y,
        right: x + boxer.width(),
        bottom: y + boxer.height()
      };
      var runner = $("#runner");
      lastTime = new Date().getTime();
      lastPosition = {
        x: x,
        y: y + boxer.height()
      };
      run(runner);
    });
  </script>
  <style type="text/css" >
  body { margin:0; padding:0; }
  #box { margin:0 auto; width:500px; height:500px; border:3px solid #DDDDDD; border-radius:4px; -wekit-border-radius:4px; -moz-border-radius:4px;}
  #runner { width:10px; height:10px; font-size:10px; color:black; padding:0; position:absolute; left:100px; top:480px;}
  </style>
</head>
<body>
<div id="box">
<div id="runner">●</div>
</div>
</body>
</html>

jQuery 특수 효과와 관련된 더 많은 콘텐츠에 관심이 있는 독자는 이 사이트의 특별 주제인 "

jQuery의 일반적인 클래식 특수 효과 요약" 및 "jQuery 애니메이션 요약"을 확인할 수 있습니다. 및 특수효과 활용"

이 기사가 jQuery 프로그래밍에 종사하는 모든 사람에게 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.