vue3+threejs新手从零开发卡牌游戏(二十):添加卡牌被破坏进入墓地逻辑

在game目录下新建graveyard文件夹存放墓地相关代码:

game/graveyard/p1.vue,这里主要设置了墓地group的位置:

<template>
  <div></div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, onBeforeUnmount, watch, defineComponent, getCurrentInstance, nextTick } from 'vue'
import { useCommonStore } from "@/stores/common.ts"
import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
import { Card } from "@/views/game/Card.ts"
import { CARD_DICT } from "@/utils/dict/card.ts"
import { transPos, renderDeckText } from "@/utils/common.ts"

// 引入threejs变量
const {proxy} = getCurrentInstance()
const THREE = proxy['THREE']
const scene = proxy['scene']
const camera = proxy['camera']
const renderer = proxy['renderer']
const TWEEN = proxy['TWEEN']

const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();

const commonStore = useCommonStore()

// 墓地group
const deckGroup = new THREE.Group()
deckGroup.name = "p1_graveyardGroup"
scene.add(deckGroup)

const init = () => {
  setDeckPos()
}

// 设置墓地位置
const setDeckPos = () => {
  nextTick(() => {
    let sitePlane = scene.getObjectByName("己方战域Plane")
    let siteDeckMesh = sitePlane.getObjectByName("己方墓地")
    let pos = new THREE.Vector3(0, 0, 0)
    siteDeckMesh.getWorldPosition(pos)
    deckGroup.position.set(pos.x, pos.y, pos.z)
    deckGroup.userData["position"] = pos
    deckGroup.scale.set(0.8, 0.8, 0.8) // 缩放
  })
}

defineExpose({
  init,
})
</script>

<style lang="scss" scoped>
</style>

然后在utils/common.ts文件中添加修改墓地和渲染墓地文字的方法(参考卡组相关方法):


// 修改墓地
const editGraveyardCard = (group:any, mesh: any, type: any) => {
  return new Promise((resolve, reject) => {
    let text = group.children.find((v: any) => v.name === "墓地数量")
    let shadowText = group.children.find((v: any) => v.name === "墓地数量阴影")
    // console.log(22, group.children, commonStore.$state.p1Deck)
    if (type === "remove") { // 删除墓地中的卡牌
      let child = group.children.find((v: any) => v.name === mesh.name)
      if (child) {
        group.remove(child)
      }
    }
    group.remove(text)
    group.remove(shadowText)
    group.children.forEach((v: any, i: any) => {
      v.position.set(0, 0.005 * i, 0)
    })
    resolve(true)
  })
}
export { editGraveyardCard }

// 渲染墓地文字
const renderGraveyardText = (group: any, text: any, font: any, position: any) => {
  return new Promise((resolve, reject) => {
    const geometry = new TextGeometry( `${text}`, {
      font,
      size: 0.4,
      height: 0,
      curveSegments: 4,
      bevelEnabled: true,
      bevelThickness: 0,
      bevelSize: 0,
      bevelSegments: 0
    });
    geometry.center()
    const material = new THREE.MeshBasicMaterial({ 
      color: new THREE.Color("white"),
      alphaHash: true
    })
    const mesh = new THREE.Mesh( geometry, material ) ;
    mesh.position.set(position.x, position.y + 0.01, position.z)
    // mesh.position.set(0, 0.005 * commonStore.$state.p1Deck.length + 0.01, 0)
    mesh.rotateX(-90 * (Math.PI / 180)) // 弧度
    mesh.name = "墓地数量"
  
    // 阴影
    let shadowGeometry = geometry.clone()
    shadowGeometry.translate(0.02, 0.02, 0);
    let shadowMaterial = new THREE.MeshBasicMaterial({
      color: new THREE.Color("black"),
      alphaHash: true
    });
    let shadowMesh = new THREE.Mesh(shadowGeometry, shadowMaterial);
    shadowMesh.position.set(position.x, position.y, position.z)
    // shadowMesh.position.set(0, 0.005 * commonStore.$state.p1Deck.length, 0)
    shadowMesh.rotateX(-90 * (Math.PI / 180)) // 弧度
    shadowMesh.name = "墓地数量阴影"
  
    group.add(mesh)
    group.add(shadowMesh)

    resolve(true)
  })
}
export { renderGraveyardText }

然后我们修改game/index.vue中的fight战斗方法,卡牌被破坏后不直接将其从scene中移除,而且改为进入墓地:

// 战斗
const fight = () => {
  if (selectedCard.value && selectedTargetCard.value) {
    let _selectedCard: any = selectedCard.value
    let _selectedTargetCard: any = selectedTargetCard.value
    if (selectedCard.value.name === "攻击力") {
      _selectedCard = _selectedCard.value.parent
    }
    if (selectedTargetCard.value.name === "攻击力") {
      _selectedTargetCard = _selectedTargetCard.value.parent
    }

    // 移除卡牌
    const removeCard = async (card: any) => {
      if (card.children && card.children.length > 0) {
        card.children.forEach((v: any) => {
          card.remove(v)
        })
      }
      console.log(321, card)
      let areaType = card.userData.areaType
      let isP1 = areaType.indexOf("己方") > -1
      let graveyardGroup = null
      let graveyardGroupPos = new THREE.Vector3(0, 0, 0)
      let cards = []
      card.material.forEach((v: any) => {
        v.transparent = false
        v.opacity = 1
        v.alphaTest = 0.1;
      })
      card.rotateX(180 * (Math.PI / 180)) // 弧度
      if (isP1) {
        card.userData.areaType = "己方墓地"
        graveyardGroup = scene.getObjectByName("p1_graveyardGroup")
        graveyardGroup.getWorldPosition(graveyardGroupPos)
        card.position.set(graveyardGroupPos.x, graveyardGroupPos.y, graveyardGroupPos.z)
        cards = scene.children.filter((v: any) => v.userData?.areaType === "己方墓地")
      } else {
        card.userData.areaType = "对方墓地"
        graveyardGroup = scene.getObjectByName("p2_graveyardGroup")
        graveyardGroup.getWorldPosition(graveyardGroupPos)
        card.position.set(graveyardGroupPos.x, graveyardGroupPos.y, graveyardGroupPos.z)
        cards = scene.children.filter((v: any) => v.userData?.areaType === "对方墓地")
      }
    
      // 修改墓地
      let position = new THREE.Vector3(0, 0.005 * cards.length, 0)
      await editGraveyardCard(graveyardGroup, card, "remove")
      await renderGraveyardText(graveyardGroup, `${cards.length}`, commonStore.$state._font, position)

      if (isP1) {
        let sitePlane = scene.getObjectByName("己方战域Plane")
        let mesh = sitePlane.children.find((v: any) => v.name === areaType)
        if (mesh) {
          mesh.userData.empty = true
        }
      } else {
        let sitePlane = scene.getObjectByName("对方战域Plane")
        let mesh = sitePlane.children.find((v: any) => v.name === areaType)
        if (mesh) {
          mesh.userData.empty = true
        }
      }
    }

    cardAttack(_selectedCard, _selectedTargetCard, () => {
      console.log(888, Number(_selectedCard.userData.ATK), Number(_selectedTargetCard.userData.ATK))
      if (Number(_selectedCard.userData.ATK) > Number(_selectedTargetCard.userData.ATK)) {
        cardDestroy(_selectedTargetCard, () => {
          removeCard(_selectedTargetCard)
        })
      } else if (Number(_selectedCard.userData.ATK) === Number(_selectedTargetCard.userData.ATK)) {
        cardDestroy(_selectedCard, () => {
          removeCard(_selectedCard)
        })
        cardDestroy(_selectedTargetCard, () => {
          removeCard(_selectedTargetCard)
        })
      } else {
        cardDestroy(_selectedCard, () => {
          removeCard(_selectedCard)
        })
      }
    })
    selectedCard.value = null
    selectedTargetCard.value = null
  }
}

页面效果如下:

附:
game/index.vue完整代码:

<template>
  <div ref="sceneRef" class="scene"></div>
  <!-- 玩家区 -->
  <Player ref="playerRef"/>
  <!-- 手牌 -->
  <Hand ref="handRef"/>
  <!-- 卡组 -->
  <Deck ref="deckRef"/>
  <!-- 战域 -->
  <Site ref="siteRef"/>
  <!-- 墓地 -->
  <Graveyard ref="graveyardRef"/>
  <!-- 抽卡逻辑 -->
  <DrawCard ref="drawCardRef" :handRef="handRef"/>
  <!-- 对话框 -->
  <Dialog ref="dialogRef" @handToSite="handToSite" @onCancel="onCancel"/>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, onBeforeUnmount, watch, defineComponent, getCurrentInstance, nextTick } from 'vue'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; // 轨道控制器
import { DragControls } from 'three/addons/controls/DragControls.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { GlitchPass } from 'three/addons/postprocessing/GlitchPass.js';
import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
import { GammaCorrectionShader } from 'three/examples/jsm/shaders/GammaCorrectionShader.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
import { OutlinePass } from 'three/examples/jsm/postprocessing/OutlinePass.js';
import { FontLoader } from 'three/addons/loaders/FontLoader.js';
import { useCommonStore } from "@/stores/common.ts"
import { transPos, editDeckCard, renderDeckText, editGraveyardCard, renderGraveyardText, renderSiteCardText, cardAttack, cardDestroy } from "@/utils/common.ts"
import { Card } from "./Card.ts"
import { CARD_DICT } from "@/utils/dict/card.ts"
import { p1TestDeck, p2TestDeck} from "@/utils/deck/test.ts"
import Hand from "./hand/index.vue"
import Deck from "./deck/index.vue"
import Site from "./site/index.vue"
import Player from "./player/index.vue"
import Graveyard from "./graveyard/index.vue"
import DrawCard from "@/components/DrawCard.vue"
import Dialog from "@/components/Dialog.vue"
import { resolve } from 'dns';

// 引入threejs变量
const {proxy} = getCurrentInstance()
const THREE = proxy['THREE']
const scene = proxy['scene']
const camera = proxy['camera']
const renderer = proxy['renderer']
const composer = proxy['composer']
const TWEEN = proxy['TWEEN']

// 后期处理
const renderPass = new RenderPass( scene, camera );
composer.addPass( renderPass );

// 
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();

const commonStore = useCommonStore()


// 场景ref
const sceneRef = ref()
const playerRef = ref()
const siteRef = ref()
const handRef = ref()
const deckRef = ref()
const graveyardRef = ref()
const drawCardRef = ref()
const dialogRef = ref()
const selectedCard = ref() // 选中的场上card
const selectedTargetCard = ref() // 选中的目标场上card

// 坐标轴辅助
const axesHelper = new THREE.AxesHelper(5);
// 创建轨道控制器
// const orbitControls = new OrbitControls( camera, renderer.domElement );
// 字体加载器
const fontLoader = new FontLoader();

onMounted(async () => {
  await initResource()
  initScene()
  initGame()

  // 鼠标按下
  window.addEventListener('touchstart', onMousedown)
  window.addEventListener('touchmove', onMousemove)
  window.addEventListener('touchend', onMouseup)
  // window.addEventListener('click', onMousedown)

  // 监听浏览器窗口变化进行场景自适应
  window.addEventListener('resize', onWindowResize, false);
})

// 资源加载
const initResource = () => {
  // 字体加载
  return new Promise((resolve, reject) => {
    // Microsoft YaHei_Regular
    // fonts/helvetiker_regular.typeface.json
    fontLoader.load('fonts/helvetiker_bold.typeface.json', (font: any) => {
      commonStore.loadFont(font)
      resolve(true)
    });
  })
}

// 初始化场景
const initScene = async () => {
  renderer.setSize( window.innerWidth, window.innerHeight );
  sceneRef.value.appendChild( renderer.domElement );
  scene.add(axesHelper)
  // addSceneBg()

  // camera.position.set( 5, 5, 5 );
  camera.position.set( 0, 6.5, 0 );
  camera.lookAt(0, 0, 0)
  // const glitchPass = new GlitchPass();
  // composer.addPass( glitchPass );

  // const outputPass = new OutputPass();
  // composer.addPass( outputPass );

  addPlane()

  animate();
}

// scene添加动态背景
const addSceneBg = () => {
  const vertices = [];

  for ( let i = 0; i < 5000; i ++ ) {
    const x = THREE.MathUtils.randFloatSpread( 1000 );
    const y = THREE.MathUtils.randFloatSpread( 1000 );
    const z = THREE.MathUtils.randFloatSpread( 1000 );
    vertices.push( x, y, z );
  }

  const particlesGeometry = new THREE.BufferGeometry();
  particlesGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );

  // 设置点材质
  const pointsMaterial = new THREE.PointsMaterial();
  // pointsMaterial.size = 0.9;
  pointsMaterial.color.set(new THREE.Color("#fff"));
  // 相机深度而衰减
  pointsMaterial.sizeAttenuation = true;

  const points = new THREE.Points(particlesGeometry, pointsMaterial);

  scene.add(points);

  // const texture = new THREE.TextureLoader().load( "textures/bg.jpg" );
  // // const geometry = new THREE.SphereGeometry( 1, 32, 16 );
  // const geometry = new THREE.CircleGeometry( 6, 32 );
  // const material = new THREE.MeshBasicMaterial({
  //   map: texture
  // });
  // const sphere = new THREE.Mesh( geometry, material );
  // sphere.name = "场景背景"
  // sphere.position.set(0, 0, 0)
  // sphere.rotateX(-90 * (Math.PI / 180)) // 弧度
  // scene.add( sphere );

  // texture.wrapS = THREE.RepeatWrapping;
  // texture.wrapT = THREE.RepeatWrapping;
  // scene.background = texture
}

// scene中添加plane几何体
const addPlane = () => {
  const geometry = new THREE.PlaneGeometry( 20, 20);
  const material = new THREE.MeshBasicMaterial( {
    color: new THREE.Color("gray"), 
    side: THREE.FrontSide, 
    alphaHash: true,
    // alphaTest: 0,
    opacity: 0
  } );
  const plane = new THREE.Mesh( geometry, material );
  plane.rotateX(-90 * (Math.PI / 180)) // 弧度
  plane.name = "地面"
  scene.add( plane );
}

// 用requestAnimationFrame进行渲染循环
// let bgMesh = scene.getObjectByName("场景背景")
// console.log(123, bgMesh)

// 移动线纹理
let arrowTexture = new THREE.TextureLoader().load('textures/arrow.png');
arrowTexture.wrapT = THREE.RepeatWrapping;
arrowTexture.repeat.set(1, 4);
arrowTexture.center = new THREE.Vector2(0.5, 0.5)
arrowTexture.rotation = (-90 * (Math.PI / 180))
arrowTexture.needsUpdate = true;

const animate = () => {
  requestAnimationFrame( animate );
  if (arrowTexture) {
    arrowTexture.offset.y -= 0.02; //更新箭头纹理偏移量
  }
  TWEEN.update()
  // let bgMesh = scene.getObjectByName("场景背景")
  // if (bgMesh) {
  //   bgMesh.rotation.z += 0.0002
  // }
  // renderer.render( scene, camera );
  composer.render()
}

// 场景跟随浏览器窗口大小自适应
const onWindowResize = () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
}

// 初始化游戏
const initGame = async () => {
  // 初始化玩家
  initPlayer()
  // 初始化场地
  initSite()
  // 初始化墓地
  initGraveyard()
  // 初始化卡组
  await initDeck()
  // 初始化手牌
  await initHand()
  // 绑定手牌事件
  onHandEvent()

  // 
  await p2DrawCardEvent(1)
  let p2_handGroup = scene.getObjectByName("p2_handGroup")
  let cards = p2_handGroup.children.filter((v: any) => v.userData.type === "怪兽")
  p2HandToSite(cards[0])
}

// 初始化玩家
const initPlayer = () => {
  playerRef.value.init()
}

// 初始化场地
const initSite = () => {
  siteRef.value.init()
}

// 初始化墓地
const initGraveyard = () => {
  graveyardRef.value.init()
}

// 初始化卡组
const initDeck = () => {
  return new Promise((resolve, reject) => {
    let p1Deck: any = []
    let p2Deck: any = []
    // 洗牌
    p1TestDeck.sort(() => {
      return Math.random() - 0.5
    })
    p2TestDeck.sort(() => {
      return Math.random() - 0.5
    })
    p1TestDeck.forEach((v: any, i: any) => {
      let obj = CARD_DICT.find((b: any) => b.card_id === v)
      if (obj) {
        p1Deck.push({
          card_id: v,
          name: `${obj.name}_${i}`
        })
      }
    })
    p2TestDeck.forEach((v: any, i: any) => {
      let obj = CARD_DICT.find((b: any) => b.card_id === v)
      if (obj) {
        p2Deck.push({
          card_id: v,
          name: `${obj.name}_${i}`
        })
      }
    })
    // console.log("p1Deck", newDeck)
    commonStore.updateP1Deck(p1Deck)
    commonStore.updateP2Deck(p2Deck)
    
    nextTick(() => {
      handRef.value.init()
      deckRef.value.init()
      resolve(true)
    })
  })
}

// 初始化手牌
const initHand = () => {
  let p1 = new Promise((resolve, reject) => {
    let cardNumber = 4
    let _number = 0
    let p1Deck = JSON.parse(JSON.stringify(commonStore.$state.p1Deck))
    let deckGroup = scene.getObjectByName("p1_deckGroup")
    let position = new THREE.Vector3(0, 0.005 * p1Deck.length, 0)
    let _interval = setInterval(async() => {
      // console.log(123, p1Deck)
      if (_number < cardNumber) {
        let obj = p1Deck[p1Deck.length - 1]
        p1Deck.splice(p1Deck.length-1, 1)
        commonStore.updateP1Deck(p1Deck)
        // 修改卡组
        await editDeckCard(deckGroup, obj, "remove")
        await renderDeckText(deckGroup, `${commonStore.$state.p1Deck.length}`, commonStore.$state._font, position)
        // 手牌区添加手牌
        handRef.value.addP1HandCard(obj, deckGroup)
      } else {
        clearInterval(_interval)
        resolve(true)
      }
      _number++
    }, 200)
  })

  let p2 = new Promise((resolve, reject) => {
    let cardNumber = 4
    let _number = 0
    let p2Deck = JSON.parse(JSON.stringify(commonStore.$state.p2Deck))
    let deckGroup = scene.getObjectByName("p2_deckGroup")
    let position = new THREE.Vector3(0, 0.005 * p2Deck.length, 0)
    let _interval = setInterval(async() => {
      // console.log(123, p1Deck)
      if (_number < cardNumber) {
        let obj = p2Deck[p2Deck.length - 1]
        p2Deck.splice(p2Deck.length-1, 1)
        commonStore.updateP2Deck(p2Deck)
        // 修改卡组
        await editDeckCard(deckGroup, obj, "remove")
        await renderDeckText(deckGroup, `${commonStore.$state.p2Deck.length}`, commonStore.$state._font, position)
        // 手牌区添加手牌
        handRef.value.addP2HandCard(obj, deckGroup)
      } else {
        clearInterval(_interval)
        resolve(true)
      }
      _number++
    }, 200)
  })
  return new Promise((resolve, reject) => {
    Promise.all([p1, p2]).then((res: any) => {
      resolve(true)
    })
  })
}

// p2抽牌事件
const p2DrawCardEvent = (cardNumber: any) => {
  return new Promise((resolve, reject) => {
    let _number = 0
    let p2Deck = JSON.parse(JSON.stringify(commonStore.$state.p2Deck))
    let deckGroup = scene.getObjectByName("p2_deckGroup")
    let position = new THREE.Vector3(0, 0.005 * p2Deck.length, 0)
    let _interval = setInterval(async() => {
      // console.log(123, p1Deck)
      if (_number < cardNumber) {
        let obj = p2Deck[p2Deck.length - 1]
        p2Deck.splice(p2Deck.length-1, 1)
        commonStore.updateP2Deck(p2Deck)
        // 修改卡组
        await editDeckCard(deckGroup, obj, "remove")
        await renderDeckText(deckGroup, `${commonStore.$state.p2Deck.length}`, commonStore.$state._font, position)
        // 手牌区添加手牌
        handRef.value.addP2HandCard(obj, deckGroup)
      } else {
        clearInterval(_interval)
        resolve(true)
      }
      _number++
    }, 200)
  })
}

// p2卡牌上场事件
const p2HandToSite = (card: any) => {
  let sitePlane = scene.getObjectByName("对方战域Plane")
  let userData = card.userData
  if (userData.type === "怪兽") {
    let meshes = sitePlane.children.filter((v: any) => v.name.indexOf("对方怪兽区") > -1 && v.userData.empty === true)
    if (meshes.length > 0) {
      let _mesh = null
      let m1 = meshes.find((v: any) => v.name.indexOf(1) > -1)
      let m2 = meshes.find((v: any) => v.name.indexOf(2) > -1)
      let m3 = meshes.find((v: any) => v.name.indexOf(3) > -1)
      if (m2) {
        _mesh = m2
      } else if (m1) {
        _mesh = m1
      } else if (m3) {
        _mesh = m3
      }
      let p2_handGroup = scene.getObjectByName("p2_handGroup")
      // card.rotateX(180 * (Math.PI / 180)) // 弧度
      renderSiteCard(p2_handGroup, card, _mesh)
    }
  }
}

// 鼠标按下事件
const onMousedown = (ev: any) => {
  // console.log(222, ev.target)
  // 判断是否点击到canvas上
  if(!(ev.target instanceof HTMLCanvasElement)){
    return;
  }
  // 将鼠标位置归一化为设备坐标。x 和 y 方向的取值范围是 (-1 to +1)
  let clientX = ev.clientX || ev.changedTouches[0].pageX
  let clientY = ev.clientY || ev.changedTouches[0].pageY

  let point = transPos(clientX, clientY)

  // 通过摄像机和鼠标位置更新射线
  raycaster.setFromCamera( point, camera );
  
  // 点击卡组事件
  // onP1DeckEvent()
  // 鼠标选中场上卡牌事件
  onSelectSiteCard()
}

// 鼠标移动事件
const onMousemove = (ev: any) => {
  // 将鼠标位置归一化为设备坐标。x 和 y 方向的取值范围是 (-1 to +1)
  pointer.x = ev.clientX || ev.changedTouches[0].pageX
  pointer.y = ev.clientY || ev.changedTouches[0].pageY
  // 画线
  if (selectedCard.value) {
    drawLine()
  }
}

// 鼠标抬起事件
const onMouseup = (ev: any) => {
  let lineMesh = scene.getObjectByName("移动线")
  if (lineMesh) {
    scene.remove(lineMesh)
  }
  fight()
}

// 鼠标选中场上卡牌事件
const onSelectSiteCard = () => {
  let p1Cards = scene.children.filter((v: any) => v.userData?.areaType?.indexOf("己方怪兽区") > -1)
  if (p1Cards.length <= 0) {
    return
  }
  let arr = raycaster.intersectObjects(p1Cards, true)
  if (arr.length > 0) {
    selectedCard.value = arr[0].object
    // drawLine()
  }

}

// 画线
const drawLine = () => {
  let mesh = scene.getObjectByName("移动线")
  if (mesh) {
    scene.remove(mesh)
  }
  
  let startPos = new THREE.Vector3(0, 0, 0)
  selectedCard.value.getWorldPosition(startPos)
  let point = transPos(pointer.x, pointer.y)
  
  // 通过摄像机和鼠标位置更新射线
  raycaster.setFromCamera( point, camera );

  let plane = scene.getObjectByName("地面")
  let arr = raycaster.intersectObject(plane)
  if (arr.length > 0) {
    // let pos = new THREE.Vector3(0, 0, 0)
    // arr[0].object.getWorldPosition(pos)
    let point = arr[0].point
    let curve = new THREE.CatmullRomCurve3([
      new THREE.Vector3(startPos.x, startPos.y + 0.2, startPos.z),
      new THREE.Vector3(point.x, point.y + 0.2, point.z)
      
    ]);
    let tubeGeometry = new THREE.TubeGeometry(curve, 80, 0.08);

    const material = new THREE.MeshBasicMaterial({
      map: arrowTexture,
      side: THREE.BackSide, //显示背面
      transparent: true,
      // color: new THREE.Color("#ff6347")
    });
    const _mesh = new THREE.Mesh( tubeGeometry, material );
    _mesh.name = "移动线"
    scene.add(_mesh);
  }
  
  // 获取目标对象
  getTargetMesh()
}

// 获取目标对象
const getTargetMesh = () => {
  let p2Cards = scene.children.filter((v: any) => v.userData?.areaType?.indexOf("对方怪兽区") > -1)
  if (p2Cards.length <= 0) {
    selectedTargetCard.value = null
    return
  }
  let arr = raycaster.intersectObjects(p2Cards, true)
  if (arr.length > 0) {
    selectedTargetCard.value = arr[0].object
  } else {
    selectedTargetCard.value = null
  }
}

// 战斗
const fight = () => {
  if (selectedCard.value && selectedTargetCard.value) {
    let _selectedCard: any = selectedCard.value
    let _selectedTargetCard: any = selectedTargetCard.value
    if (selectedCard.value.name === "攻击力") {
      _selectedCard = _selectedCard.value.parent
    }
    if (selectedTargetCard.value.name === "攻击力") {
      _selectedTargetCard = _selectedTargetCard.value.parent
    }

    // 移除卡牌
    const removeCard = async (card: any) => {
      if (card.children && card.children.length > 0) {
        card.children.forEach((v: any) => {
          card.remove(v)
        })
      }
      console.log(321, card)
      let areaType = card.userData.areaType
      let isP1 = areaType.indexOf("己方") > -1
      let graveyardGroup = null
      let graveyardGroupPos = new THREE.Vector3(0, 0, 0)
      let cards = []
      card.material.forEach((v: any) => {
        v.transparent = false
        v.opacity = 1
        v.alphaTest = 0.1;
      })
      card.rotateX(180 * (Math.PI / 180)) // 弧度
      if (isP1) {
        card.userData.areaType = "己方墓地"
        graveyardGroup = scene.getObjectByName("p1_graveyardGroup")
        graveyardGroup.getWorldPosition(graveyardGroupPos)
        card.position.set(graveyardGroupPos.x, graveyardGroupPos.y, graveyardGroupPos.z)
        cards = scene.children.filter((v: any) => v.userData?.areaType === "己方墓地")
      } else {
        card.userData.areaType = "对方墓地"
        graveyardGroup = scene.getObjectByName("p2_graveyardGroup")
        graveyardGroup.getWorldPosition(graveyardGroupPos)
        card.position.set(graveyardGroupPos.x, graveyardGroupPos.y, graveyardGroupPos.z)
        cards = scene.children.filter((v: any) => v.userData?.areaType === "对方墓地")
      }
    
      // 修改墓地
      let position = new THREE.Vector3(0, 0.005 * cards.length, 0)
      await editGraveyardCard(graveyardGroup, card, "remove")
      await renderGraveyardText(graveyardGroup, `${cards.length}`, commonStore.$state._font, position)

      if (isP1) {
        let sitePlane = scene.getObjectByName("己方战域Plane")
        let mesh = sitePlane.children.find((v: any) => v.name === areaType)
        if (mesh) {
          mesh.userData.empty = true
        }
      } else {
        let sitePlane = scene.getObjectByName("对方战域Plane")
        let mesh = sitePlane.children.find((v: any) => v.name === areaType)
        if (mesh) {
          mesh.userData.empty = true
        }
      }
    }

    cardAttack(_selectedCard, _selectedTargetCard, () => {
      console.log(888, Number(_selectedCard.userData.ATK), Number(_selectedTargetCard.userData.ATK))
      if (Number(_selectedCard.userData.ATK) > Number(_selectedTargetCard.userData.ATK)) {
        cardDestroy(_selectedTargetCard, () => {
          removeCard(_selectedTargetCard)
        })
      } else if (Number(_selectedCard.userData.ATK) === Number(_selectedTargetCard.userData.ATK)) {
        cardDestroy(_selectedCard, () => {
          removeCard(_selectedCard)
        })
        cardDestroy(_selectedTargetCard, () => {
          removeCard(_selectedTargetCard)
        })
      } else {
        cardDestroy(_selectedCard, () => {
          removeCard(_selectedCard)
        })
      }
    })
    selectedCard.value = null
    selectedTargetCard.value = null
  }
}

// 点击卡组事件
const onP1DeckEvent = () => {
  if (commonStore.$state.p1Deck.length <= 0) {
    return
  }
  let p1_deckGroup = scene.getObjectByName("p1_deckGroup")
  let arr = raycaster.intersectObject(p1_deckGroup, true)
  if (arr.length <= 0) {
    return
  }
  let pos1 = p1_deckGroup.userData.position
  let pos2 = new THREE.Vector3(0, 2, 0)
  // console.log(444, pos1, pos2)
  if (p1_deckGroup.position.x !== pos2.x) {
    drawCardRef.value.drawCardAnimate1(p1_deckGroup, pos1, pos2)
  }
}


// 手牌事件
const onHandEvent = () => {
  let handGroup = scene.getObjectByName("p1_handGroup")
  const dragControls = new DragControls( handGroup.children, camera, renderer.domElement );

  dragControls.addEventListener( 'dragstart', function ( event: any ) {
    event.object.position.y += 0.04
  });

  dragControls.addEventListener( 'drag', function ( event: any ) {
    event.object.position.y += 0.04
    
  });

  dragControls.addEventListener( 'dragend', function ( event: any ) {
    event.object.position.y -= 0.04
    let p1SitePlane = scene.getObjectByName("己方战域Plane")
    let point = transPos(pointer.x, pointer.y)
    // 通过摄像机和鼠标位置更新射线
    raycaster.setFromCamera( point, camera );
    const intersects = raycaster.intersectObjects(p1SitePlane.children);
    if (intersects.length > 0) {
      dialogRef.value.init({
        type: "handToSite",
        obj: event.object,
        message: "是否上场该卡牌"
      })
    } else {
      handRef.value.backPosition(event.object)
    }
  });
}

// 手牌移入己方战域
const handToSite = (data: any) => {
  let sitePlane = scene.getObjectByName("己方战域Plane")
  // console.log(data)
  let userData = data.userData
  if (userData.type === "怪兽") {
    let meshes = sitePlane.children.filter((v: any) => v.name.indexOf("己方怪兽区") > -1 && v.userData.empty === true)
    if (meshes.length > 0) {
      let _mesh = null
      let m1 = meshes.find((v: any) => v.name.indexOf(1) > -1)
      let m2 = meshes.find((v: any) => v.name.indexOf(2) > -1)
      let m3 = meshes.find((v: any) => v.name.indexOf(3) > -1)
      if (m2) {
        _mesh = m2
      } else if (m1) {
        _mesh = m1
      } else if (m3) {
        _mesh = m3
      }
      let p1_handGroup = scene.getObjectByName("p1_handGroup")
      renderSiteCard(p1_handGroup, data, _mesh)
    }
  }
}

// 绘制场上卡牌
const renderSiteCard = async (handGroup: any, data: any, mesh: any) => {
  let position = new THREE.Vector3(0, 0, 0)
  mesh.getWorldPosition(position)
  mesh.userData.empty = false
  let oldMesh = handGroup.children.find((v: any) => v.name === data.name)
  let newMesh = oldMesh.clone()
  newMesh.userData.areaType = mesh.name // 用来记录卡牌在哪个区域,怪兽区、墓地、手牌、卡组、场地等
  newMesh.scale.set(0.8, 0.8, 0.8)
  if (handGroup.name === "p1_handGroup") {
    handRef.value.removeP1HandCard(oldMesh)
  } else if (handGroup.name === "p2_handGroup") {
    handRef.value.removeP2HandCard(oldMesh)
    newMesh.rotateX(180 * (Math.PI / 180)) // 弧度
    newMesh.rotateY(180 * (Math.PI / 180)) // 弧度
  }
  scene.add(newMesh)
  newMesh.position.set(position.x, position.y, position.z)
  await renderSiteCardText(handGroup, newMesh, commonStore.$state._font)

  // 创建伽马校正通道
  // const gammaPass= new ShaderPass(GammaCorrectionShader)
  // composer.addPass( gammaPass );
  
  // const outlinePass = new OutlinePass(new THREE.Vector2( window.innerWidth, window.innerHeight ), scene, camera); // 模糊
  // outlinePass.edgeStrength = 1.0; // 调整边缘强度
  // outlinePass.edgeGlow = 1.0; // 边缘发光强度
  // outlinePass.usePatternTexture = false; // 是否使用纹理
  // outlinePass.visibleEdgeColor.set(0xffffff); // 设置边缘颜色
  // outlinePass.hiddenEdgeColor.set(0x000000); // 设置隐藏边缘的颜色

  // outlinePass.selectedObjects = [newMesh.children[0]]
  // composer.addPass( outlinePass );
  // console.log(123, newMesh)
}

// 取消
const onCancel = (data: any) => {
  handRef.value.backPosition(data)
}
</script>

<style lang="scss" scoped>
.scene {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
}
</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/500312.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

HTML5 和 CSS3 提高

一、HTML5 的新特性 HTML5 的新增特性主要是针对于以前的不足&#xff0c;增加了一些新的标签、新的表单和新的表单属性等。这些新特性都有兼容性问题&#xff0c;基本是 IE9 以上版本的浏览器才支持&#xff0c;如果不考虑兼容性问题&#xff0c;可以大量使用这些新特性。 声明…

架构之第三方框架pinyin4j与hutool搭配使用原理

一、工作原理 Hutool工具将包括pinyin4j等翻译工具插件绑定。实现通过spi接口的方式实现调用&#xff0c;底层实现可自由切换 注&#xff1a;Hutool绑定的pinyin插件有如下图几种。也就是没有添加maven依赖如pinyin4j等拼音插件。 注&#xff1a;若没有依赖pinyin插件。使用时…

性能与压力测试

一、性能监控 1.1 jvm内存模型—堆 由于所有的对象实例以及数组都要在堆上分配内存&#xff0c;并且堆是垃圾收集器管理的主要区域&#xff0c;也被称为“GC堆”&#xff0c;所以堆是我们优化最多考虑的地方。 首先&#xff0c;堆可细分为&#xff1a; Young区&#xff08;新…

动态规划刷题(算法竞赛、蓝桥杯)--导弹拦截(线性DP)

1、题目链接&#xff1a;[NOIP1999 提高组] 导弹拦截 - 洛谷 #include <bits/stdc.h> using namespace std; const int N2e55; int a[N],x,n; int b[N],len;int main(){while(cin>>x)a[n]x;//求最长不上升子序列 b[0]2e9;//初始化为无穷大for(int i1;i<n;i){if(…

配置visual studio code 用秘钥远程连接SSH服务器

配置visual studio code 用秘钥远程连接SSH服务器 文章目录 配置visual studio code 用秘钥远程连接SSH服务器简介1. 生成SSH密钥对2. 将公钥添加到Ubuntu服务器3. 将私钥添加到visual studio code的SSH配置文件中 简介 通过SSH密钥认证&#xff0c;用户无需在每次连接时输入密…

FFmpeg将绿幕视频处理成透明视频播放

怎么在网页端插入透明视频呢&#xff0c;之前在做Web3D项目时&#xff0c;使用threejs可以使绿幕视频透明显示在三维场景中&#xff0c;但是在网页端怎么让绿幕视频透明显示呢&#xff1f; 如图上图&#xff0c;视频背景遮挡住后面网页内容 想要如下图效果 之前有使用过ffmpeg…

《算法笔记》系列----质数的判断(埃氏筛法)

目录 一、朴素算法 二、埃氏筛法 1、与朴素算法对比 2、算法介绍 3、例题即代码实现 一、朴素算法 从素数的定义中可以知道&#xff0c;一个整数n要被判断为素数&#xff0c;需要判断n是否能被2.3.n- 1中的一个整除。只2&#xff0c;3..n- 1都不能整除n&#xff0c;n才能…

服务器被CC攻击之后怎么办?

1.取消域名绑定取消域名绑定后Web服务器的CPU能够马上恢复正常状态&#xff0c;通过IP进行访问连接一切正常。但是不足之处也很明显&#xff0c;取消或者更改域名对于别人的访问带来了不变&#xff0c;另外&#xff0c;对于针对IP的CC攻击它是无效的&#xff0c;就算更换域名攻…

HTTP 与 HTTPS 的区别

基本概念 HTTP&#xff08;HyperText Transfer Protocol&#xff1a;超文本传输协议&#xff09;是一种应用层协议&#xff0c;主要用于在网络上进行信息的传递&#xff0c;特别是用于Web浏览器和服务器之间的通信。 它使用明文方式发送数据&#xff0c;这意味着传输的内容可…

【生活】相机/图像各参数

文章目录 专业模式图片编辑-滤镜实体滤镜软件模拟滤镜 图片编辑-增强曝光亮度对比度饱和度自然饱和度色温色调高光阴影HSL色调分离褪色颗粒锐化晕影清晰度暗角 参考 专业模式 第一个参数WB是白平衡&#xff0c;调节色彩的。 第二个是对焦F&#xff0c;近距离拍摄物体&#xf…

macOS Ventura 13.6.6 (22G630) 正式版发布,ISO、IPSW、PKG 下载

macOS Ventura 13.6.6 (22G630) 正式版发布&#xff0c;ISO、IPSW、PKG 下载 3 月 26 日凌晨&#xff0c;macOS Sonoma 14.4.1 发布&#xff0c;同时带来了 macOS Ventru 13.6.6 安全更新。 macOS Ventura 13.6 及更新版本&#xff0c;如无特殊说明皆为安全更新&#xff0c;不…

电脑分辨率怎么调,电脑分辨率怎么调整

随着电脑的普及以及网络的发展&#xff0c;我们现在在工作中都离不开对电脑的使用&#xff0c;今天小编教大家设置电脑分辨率&#xff0c;现在我们先了解这个分辨率是什么?通常电脑的显示分辨率就是屏幕分辨率&#xff0c;显示屏大小固定时&#xff0c;显示分辨率越高图像越清…

关于深度学习的 PyTorch 项目如何上手分析?从什么地方切入?

文章目录 PyTorch 项目分析1.背景2.分析流程 PyTorch 项目分析 1.背景 当我们拿到一个 PyTorch 的深度学习项目时&#xff0c;应该怎么入手&#xff1f;怎么去查看代码&#xff1f; 2.分析流程 首先阅读对应项目的 README.md 文件。通过阅读 README.md &#xff0c;一般可以…

Oracle 19c 高可用部署实战系列之Data Guard理论与实战

课程介绍 Oracle Data Guard确保企业数据的高可用性、数据保护和灾难恢复。 Oracle Data Guard提供了一组全面的服务&#xff0c;用于创建、维护、管理和监视一个或多个备用数据库&#xff0c;使生产Oracle数据库能够在灾难和数据损坏中幸存下来。Oracle Data Guard将这些备用…

SpringBoot整合腾讯云邮件发送服务非STMP

SpringBoot整合腾讯云邮箱服务 1、pom配置 <!-- 腾讯云邮箱服务--><dependency><groupId>com.tencentcloudapi</groupId><artifactId>tencentcloud-sdk-java</artifactId><!-- go to https://search.maven.org/search?qtencen…

微服务demo(四)nacosfeigngateway

一、gateway使用&#xff1a; 1、集成方法 1.1、pom依赖&#xff1a; 建议&#xff1a;gateway模块的pom不要去继承父工程的pom&#xff0c;父工程的pom依赖太多&#xff0c;极大可能会导致运行报错&#xff0c;新建gateway子工程后&#xff0c;pom父类就采用默认的spring-b…

常用植被物候提取方法 (TIMESATE/R语言/Python)-3.0

文章内容仅用于自己知识学习和分享&#xff0c;如有侵权&#xff0c;还请联系并删除 &#xff1a;&#xff09; 常用植被物候提取方法 (TIMESATE/R语言/Python)-1.0见 link常用植被物候提取方法 (TIMESATE/R语言/Python)-2.0见 link 这里主要介绍一下自己读到的论文&#xff…

虚拟现实(VR)项目的开发工具

虚拟现实&#xff08;VR&#xff09;项目的开发涉及到多种工具&#xff0c;这些工具可以帮助开发者从建模、编程到最终内容的发布。以下是一些被广泛认可的VR开发工具&#xff0c;它们覆盖了从3D建模到交互设计等多个方面。北京木奇移动技术有限公司&#xff0c;专业的软件外包…

【目录整理】(五)

​​​​​Git 基础 Git 详细安装教程文章浏览阅读10w次&#xff0c;点赞9.6k次&#xff0c;收藏1.7w次。Git 是个免费的开源分布式版本控制系统&#xff0c;下载地址为git-scm.com 或者 gitforwindows.org&#xff0c;本文介绍 Git-2.40.0-64-bit.exe 版本的安装方法&#x…

华为云亮相KubeCon EU 2024,以持续开源创新开启智能时代

3月21日&#xff0c;在巴黎举办的云原生顶级峰会KubeCon EU 2024上 &#xff0c;华为云首席架构师顾炯炯在“Cloud Native x AI&#xff1a;以持续开源创新开启智能时代”的主题演讲中指出&#xff0c;云原生和AI技术的融合&#xff0c;是推动产业深刻变革的关键所在。华为云将…