three实现滑冰躲避障碍物游戏代码

代码语言:html

所属分类:游戏

代码描述:three实现滑冰躲避障碍物游戏代码,键盘左右键控制方向。

代码标签: three 滑冰 躲避 障碍物 游戏 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">

<style>
    @import url("https://fonts.googleapis.com/css?family=VT323");
*,
*:before,
*:after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  width: 100%;
  height: 100%;
  overflow: hidden;
  font-family: "VT323", monospace;
}

.footer {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 10px 10px;
  text-align: right;
  font-family: "Roboto", sans-serif;
  font-size: 12px;
}
.footer.v-dark {
  background-color: #343436;
  color: #fff;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
.footer.v-light {
  background-color: #fff;
  color: #343436;
}

.footer-anchor {
  display: inline-block;
  margin-left: 5px;
  padding: 2px 4px;
  color: #343436;
  text-decoration: none;
  background-color: #fcd000;
  border-radius: 4px;
  opacity: 1;
  transition: opacity 0.2s;
}
.footer-anchor:hover {
  opacity: 0.6;
}

#three-container {
  position: absolute;
  left: 0;
  top: 0;
}

#ui-container {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}

.flex-container {
  display: flex;
  height: 100%;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.button {
  position: relative;
  font-size: 80px;
  padding: 12px;
  background: black;
  color: #e9f259;
  cursor: pointer;
}

.button:hover {
  box-shadow: #d46ce7 10px 10px 0 0;
}

.title {
  font-size: 80px;
  line-height: 1;
  margin-bottom: 40px;
}

.score {
  font-size: 40px;
  line-height: 1;
  margin-bottom: 56px;
}

.score-display {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  /*color: #89aee1;*/
  color: black;
  font-size: 120px;
  text-align: center;
}

.life-display {
  position: absolute;
  left: 12px;
  top: 12px;
}

.live-item {
  display: inline-block;
  width: 64px;
  height: 64px;
  margin-right: 12px;
  background-image: url("//repo.bfw.wiki/bfwrepo/images/huaban/heart.png");
  background-size: contain;
}

.live-item.depleted {
  opacity: 0.25;
}
</style>
</head>
<body>


<div id="three-container"></div>
<div id="ui-container"></div>
<!-- partial -->
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/three.87.js"></script>
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/bas.2.0.2.js"></script>
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/OrbitControls.min.js"></script>
<script >
    function THREERoot(params) {
  // defaults
  params = Object.assign({
    container: '#three-container',
    fov: 60,
    zNear: 1,
    zFar: 10000,
    createCameraControls: true,
    autoStart: true,
    pixelRatio: window.devicePixelRatio,
    antialias: window.devicePixelRatio === 1,
    alpha: false },
  params);

  // maps and arrays
  this.updateCallbacks = [];
  this.resizeCallbacks = [];
  this.objects = {};

  // renderer
  this.renderer = new THREE.WebGLRenderer({
    antialias: params.antialias,
    alpha: params.alpha });

  this.renderer.setPixelRatio(params.pixelRatio);

  // container
  this.container = typeof params.container === 'string' ? document.querySelector(params.container) : params.container;
  this.container.appendChild(this.renderer.domElement);

  // camera
  this.camera = new THREE.PerspectiveCamera(
  params.fov,
  window.innerWidth / window.innerHeight,
  params.zNear,
  params.zFar);


  // scene
  this.scene = new THREE.Scene();

  // resize handling
  this.resize = this.resize.bind(this);
  this.resize();
  window.addEventListener('resize', this.resize, false);

  // tick / update / render
  this.tick = this.tick.bind(this);
  params.autoStart && this.tick();

  // optional camera controls
  params.createCameraControls && this.createOrbitControls();
}
THREERoot.prototype = {
  createOrbitControls: function () {
    this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
    this.addUpdateCallback(this.controls.update.bind(this.controls));
  },
  start: function () {
    this.tick();
  },
  addUpdateCallback: function (callback) {
    this.updateCallbacks.push(callback);
  },
  addResizeCallback: function (callback) {
    this.resizeCallbacks.push(callback);
  },
  add: function (object, key) {
    key && (this.objects[key] = object);
    this.scene.add(object);
  },
  addTo: function (object, parentKey, key) {
    key && (this.objects[key] = object);
    this.get(parentKey).add(object);
  },
  get: function (key) {
    return this.objects[key];
  },
  remove: function (o) {
    var object;

    if (typeof o === 'string') {
      object = this.objects[o];
    } else
    {
      object = o;
    }

    if (object) {
      object.parent.remove(object);
      delete this.objects[o];
    }
  },
  tick: function () {
    this.update();
    this.render();
    requestAnimationFrame(this.tick);
  },
  update: function () {
    this.updateCallbacks.forEach(function (callback) {callback();});
  },
  render: function () {
    this.renderer.render(this.scene, this.camera);
  },
  resize: function () {
    var width = window.innerWidth;
    var height = window.innerHeight;

    this.camera.aspect = width / height;
    this.camera.updateProjectionMatrix();

    this.renderer.setSize(width, height);
    this.resizeCallbacks.forEach(function (callback) {callback();});
  },
  initPostProcessing: function (passes) {
    var size = this.renderer.getSize();
    var pixelRatio = this.renderer.getPixelRatio();
    size.width *= pixelRatio;
    size.height *= pixelRatio;

    var composer = this.composer = new THREE.EffectComposer(this.renderer, new THREE.WebGLRenderTarget(size.width, size.height, {
      minFilter: THREE.LinearFilter,
      magFilter: THREE.LinearFilter,
      format: THREE.RGBAFormat,
      stencilBuffer: false }));


    var renderPass = new THREE.RenderPass(this.scene, this.camera);
    this.composer.addPass(renderPass);

    for (var i = 0; i < passes.length; i++) {
      var pass = passes[i];
      pass.renderToScreen = i === passes.length - 1;
      this.composer.addPass(pass);
    }

    this.renderer.autoClear = false;
    this.render = function () {
      this.renderer.clear();
      this.composer.render();
    }.bind(this);

    this.addResizeCallback(function () {
      var width = window.innerWidth;
      var height = window.innerHeight;

      composer.setSize(width * pixelRatio, height * pixelRatio);
    }.bind(this));
  } };

7;
</script>
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/TweenMax.min.js"></script>
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/howler.2.2.3.js"></script><script  >
    
    function _defineProperty(obj, key, value) {if (key in obj) {Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });} else {obj[key] = value;}return obj;}const GLOBAL = {
  rootURL: '//repo.bfw.wiki/bfwrepo/images/huaban/',

  colors: {
    yellow: '#e9f259',
    pink: '#d46ce7' },


  sounds: {
    bgm: 'szenia_codepen_tune2.mp3',
    score: 'smw_coin.wav',
    hit: 'smw_thud.wav' },


  textures: {
    surfer: 'internet_boy.png',

    good: [
    'apple.png',
    'clippy.png',
    'mtv.png',
    'netscape.png',
    'pokeball.png',
    'wordart.png'],


    bad: [
    'blinky.png',
    'goomba.png'] },


  anisotropy: 1,

  gameSpeed: 1.0 };


// utils

const utils = {
  getRandom(array) {
    return array[Math.random() * array.length | 0];
  } };


// Wave

class Wave extends THREE.Mesh {
  constructor(params) {
    const textureSize = 64;

    const textureCanvas = document.createElement('canvas');
    textureCanvas.width = textureCanvas.height = textureSize;

    const textureCtx = textureCanvas.getContext('2d');
    textureCtx.fillStyle = GLOBAL.colors.yellow;
    textureCtx.fillRect(0, 0, textureSize, textureSize);
    textureCtx.lineWidth = 8;
    textureCtx.strokeStyle = GLOBAL.colors.pink;
    textureCtx.strokeRect(0, 0, textureSize, textureSize);

    const texture = new THREE.CanvasTexture(textureCanvas);
    texture.wrapS = THREE.RepeatWrapping;
    texture.wrapT = THREE.RepeatWrapping;
    texture.repeat.set(50, 50);
    texture.anisotropy = GLOBAL.anisotropy;

    const model = new THREE.PlaneGeometry(100, 100, 100, 100);
    model.rotateX(-Math.PI * 0.5);

    const geometry = new BAS.ModelBufferGeometry(model);
    geometry.bufferUVs();

    const material = new BAS.BasicAnimationMaterial({
      uniformValues: {
        map: texture,
        offsetRepeat: new THREE.Vector4(0, 0, texture.repeat.x, texture.repeat.y) },

      uniforms: {
        xCurve: { value: params.xCurvePoints },
        zCurve: { value: params.zCurvePoints } },

      vertexParameters: `
        uniform vec3 xCurve[5];
        uniform vec3 zCurve[4];
      `,
      vertexFunctions: [
      BAS.ShaderChunk.catmull_rom_spline, `
        vec3 sampleOffsetX(float p) {
          float pt = p * 4.0;
          ivec4 indices = getCatmullRomSplineIndices(4.0, pt);
      
          vec3 p0 = xCurve[indices[0]];
          vec3 p1 = xCurve[indices[1]];
          vec3 p2 = xCurve[indices[2]];
          vec3 p3 = xCurve[indices[3]];
      
          return catmullRomSpline(p0, p1, p2, p3, fract(pt));
        }
        `, `
        vec3 sampleOffsetZ(float p) {
          float pt = p * 3.0;
          ivec4 indices = getCatmullRomSplineIndices(3.0, pt);
      
          vec3 p0 = zCurve[indices[0]];
          vec3 p1 = zCurve[indices[1]];
          vec3 p2 = zCurve[indices[2]];
          vec3 p3 = zCurve[indices[3]];
      
          return catmullRomSpline(p0, p1, p2, p3, fract(pt));
        }
      `],

      vertexPosition: `
        vec3 xOffset = sampleOffsetX((transformed.x + 50.0) * 0.01);
        transformed.x = xOffset.x;
        transformed.yz += xOffset.yz;
        
        vec3 zOffset = sampleOffsetZ((transformed.z + 50.0) * 0.01);
        transformed.z = zOffset.z;
        transformed.xy += zOffset.xy;
      ` });


    super(geometry, material);
  }

  update() {
    this.material.uniforms.offsetRepeat.value.y -= 0.15 * GLOBAL.gameSpeed;
  }}


// Surfer

class Surfer extends THREE.Mesh {















  constructor() {
    const geometry = new THREE.PlaneGeometry(Surfer.radius * 2, Surfer.radius * 2);
    geometry.translate(0, Surfer.radius * 0.75, 0);

    const material = new THREE.MeshBasicMaterial({
      map: new THREE.TextureLoader().load(GLOBAL.rootURL + GLOBAL.textures.surfer),
      transparent: true,
      side: THREE.DoubleSide });


    super(geometry, material);_defineProperty(this, "velocity", 0);_defineProperty(this, "idleTime", 0);_defineProperty(this, "isInvincible", false);_defineProperty(this, "isDead", false);

    this.hitbox = new THREE.Box3();
  }

  reset() {
    this.velocity = 0;
    this.idleTime = 0;
    this.isInvincible = false;
    this.isDead = false;
    this.position.set(0, Surfer.yAnchor, Surfer.zAnchor);
    this.rotation.set(0, 0, 0);
    this.scale.set(1, 1, 1);
  }

  update(keys) {
    if (this.isDead === true) return;

    // update idle wobble
    this.idleTime += 1 / 30;
    this.position.y = Surfer.yAnchor + Math.sin(this.idleTime * 4) * 0.5;

    // decay velocity
    if (this.position.x === -Surfer.xRange || this.position.x === Surfer.xRange) {
      this.velocity *= Surfer.edgeAccelerationDecay;
    } else
    {
      this.velocity *= Surfer.defaultAccelerationDecay;
    }

    // apply keys
    if (keys.left) {
      this.velocity = Math.max(-Surfer.maxVelocity, this.velocity - Surfer.acceleration * GLOBAL.gameSpeed);
    }

    if (keys.right) {
      this.velocity = Math.min(Surfer.maxVelocity, this.velocity + Surfer.acceleration * GLOBAL.gameSpeed);
    }

    this.position.x = THREE.Math.clamp(this.position.x + this.velocity, -Surfer.xRange, Surfer.xRange);

    // rotate based on velocity
    this.rotation.z = this.velocity * 0.2;

    this.hitbox.setFromObject(this);
  }

  score() {
    return TweenMax.to(this.scale, 0.25, {
      x: 0.8,
      y: 1.2,
      ease: Power3.easeIn,
      repeat: 1,
      yoyo: true });

  }

  hit() {
    this.isInvincible = true;

    let frame = 0;

    return TweenMax.to(this.rotation, 1, { y: Math.PI * 2, ease: Back.easeOut,
      onUpdate: () => {
  .........完整代码请登录后点击上方下载按钮下载查看

网友评论0