栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > Html/CSS > CSS教程

基于jQuery制作自己的web游戏引擎-贰

CSS教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于jQuery制作自己的web游戏引擎-贰

基于jQuery制作自己的web游戏引擎-贰
本章节衔接基于jQuery制作自己的web游戏引擎

第二部分:编写物理引擎
作为一个游戏引擎,物理部分是必不可少的,所以,我们即将开始编写physics.js

首先要开始编写碰撞检测,定义一个函数:

function collision(obj1,obj2) {
    if (
 ((obj1.x + obj1.width) >= obj2.x) &&
 (obj1.x <= (obj2.x + obj2.width)) &&
 ((obj1.y + obj1.height) >= obj2.y) &&
 (obj1.y <= (obj2.y + obj2.height))
    )
    {
 return true;
    } else {
 return false;
    }
}

那么如果想要知道一个game object是否有撞上任意其他游戏对象呢?

function collisionObj(obj1) {
    var collObj = [];
    for (var i = 0 ; i < gameObjs.length ; i++){
 if (gameObjs[i] !== obj1){
     if (collision(obj1,gameObjs[i])){
  collObj.push(gameObjs[i].name);
     }
 }
    }
    return collObj;
}

在现实生活中,两个物体相撞后,会因反作用力向相反方向运动,所以可以写一个rebound()函数进行该操作

function rebound(obj1,obj2) {
    obj1.define("force",true);
    obj2.define("force",true);
    if (collision(obj1,obj2)){
 obj1.angle = 180 - obj1.angle;
 obj2.angle = 180 - obj2.angle;

 var tmp = obj1.speed;
 obj1.speed += obj2.speed;
 obj2.speed += tmp;
    }
}

与reboundUpdate()

function reboundUpdate(obj1) {
    if (!obj1.get("force")){
 return null;
    }
    var rebObj = [];
    for (var i = 0 ; i < gameObjs.length ; i++){
 if (gameObjs[i] !== obj1){
     rebound(obj1,gameObjs[i])
 }
    }
    return rebObj;
}

现在物理引擎搭建完毕,接下来就可以编写游戏啦~
physics部分[完]

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/243040.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号