# 02 创建实体

(点击->高清B站视频) (opens new window)


1.从模型库生成一个模型到场景

//1.从模型库生成一个模型到场景
const meshScale = 1/16 //默认模型方块大小倍数为地图方块的1/16
world.createEntity({
    mesh:'mesh/茂盛的草.vb',//模型名
    collides:false,//能碰撞
    fixed:true,//固定
    gravity:false,//受重力影响
    meshScale:[meshScale,meshScale,meshScale],//xyz放大倍数
    position:[63,10,63],//位置坐标
})

2.改代码,生成多种模型到场景

// 2 改代码, 生成多种模型到场景
function spawn(x,y,z,meshName){
  const meshScale = 1/16 //默认模型方块大小倍数为地图方块的1/16
  return world.createEntity({
    mesh:meshName,//模型名
    collides:false,//能碰撞
    fixed:true,//固定
    gravity:false,//受重力影响
    meshScale:[meshScale,meshScale,meshScale],//xyz放大倍数
    position:[x,y,z],//位置坐标
  })
}
spawn(63,10,63,'mesh/茂盛的草.vb')
spawn(63,10,65,'mesh/花.vb')
spawn(63,10,67,'mesh/树.vb')

3.用for循环随机生成树林

//3 用for循环随机生成树林(先用一个for循环只生成草地, 然后再演示后两个for循环把花和树加进来)
function spawn(x,y,z,meshName,scale){
  const meshScale = scale/16 //默认模型方块大小倍数为地图方块的1/16
  return world.createEntity({
    mesh:meshName,//模型名
    collides:false,//能碰撞
    fixed:true,//固定
    gravity:false,//受重力影响
    meshScale:[meshScale,meshScale,meshScale],//xyz放大倍数
    position:[x,y,z],//位置坐标
  })
}

for(var i=0;i<800;i++){
  spawn(Math.random()*127,9,Math.random()*127,'mesh/茂盛的草.vb',1)
}

for(var i=0;i<50;i++){
  spawn(Math.random()*127,9,Math.random()*127,'mesh/花.vb',1)
}

for(var i=0;i<100;i++){
  spawn(Math.random()*127,9,Math.random()*127,'mesh/树.vb',3+3*Math.random())
}

4.修改代码,修正模型Y坐标使模型完全露出地面,并给树木加碰撞

//4 修改代码, 修正模型Y坐标使模型完全露出地面, 并给树木加碰撞
function spawn(x,y,z,meshName,scale){
  const meshScale = scale/16 //默认模型方块大小倍数为地图方块的scale/16
  const entity = world.createEntity({
    mesh:meshName,//模型名
    collides:false,//能碰撞
    fixed:true,//固定
    gravity:false,//受重力影响
    meshScale:[meshScale,meshScale,meshScale],//xyz放大倍数
    position:[x,y,z],//位置坐标
  })
  correctY(entity)
  return entity
}

for(var i=0;i<800;i++){
  spawn(Math.random()*127,9,Math.random()*127,'mesh/茂盛的草.vb',1)
}

for(var i=0;i<50;i++){
  spawn(Math.random()*127,9,Math.random()*127,'mesh/花.vb',1)
}

for(var i=0;i<100;i++){
  let tree = spawn(Math.random()*127,9,Math.random()*127,'mesh/树.vb',3+3*Math.random())
  tree.collides = true
}

async function correctY(entity){
  await sleep(1)//entity.bounds需要等到下一个tick才会变成真正的值
  entity.position.y += entity.bounds.y//bounds.y是中心点到模型顶部或底部的距离
}