Unity3D学习笔记——Android重力感应控制小球

一:准备资源
      
           该文章出自【狗刨学习网】
    两张贴图:地图和小球贴图。

            

二:导入资源

    在Assets下建立resources文件夹,然后将贴图导入。

     
     

三:建立场景游戏对象

    1.建立灯光:

     
     

    2.创建一个相机,配置默认。

     

    3.建立一个Plane用来表示地面,将导入的地面图片付给Plane。

     
     

    4:建立一个小球,并为其添加一个刚体,因为之后会通过重力感应为小球添加外部作用力,所以需要有刚体组件。

     
     

三:创建脚本

    1.控制小球运动的脚本:首先要将手机的重力感应控件坐标转换为游戏世界的空间坐标。

      

     建立一个C#脚本:

      
  1. <font color="#000000" face="宋体" size="3">using UnityEngine;
  2. using System.Collections;

  3. public class BallControl : MonoBehaviour
  4. {
  5.         //移动速度
  6.         public int speed = 10;
  7.     
  8.         void Update ()
  9.         {
  10.                 //建立一个向量变量,将手机向量坐标改变为游戏向量坐标
  11.                 Vector3 dir = Vector3.zero;
  12.                 dir.z = Input.acceleration.y;
  13.                 dir.x = Input.acceleration.x;

  14.                 //钳制加速度向量到单位球
  15.                 if (dir.sqrMagnitude > 1)
  16.                         dir.Normalize ();

  17.                 //使它每秒移动10米,而不是每帧10米
  18.                 dir *= Time.deltaTime;
  19.         
  20.                 // Move object 移动物体
  21.                 rigidbody.AddForce (dir * speed, ForceMode.Force);
  22.         }
  23. }</font>
复制代码



    将这个脚本附加给小球:

     

    Speed:小球运动的速度。

    2.控制相机脚本,使相机跟随小球移动

          

  1. <font color="#000000" face="宋体" size="3">using UnityEngine;
  2. using System.Collections;

  3. public class CameraControl : MonoBehaviour
  4. {
  5.         public Transform target;
  6.         public int relativeHeight = 10;
  7.         public int zDistance = 1;
  8.         public int dampSpeed = 1;
  9.     
  10.         // Update is called once per frame
  11.         void Update ()
  12.         {
  13.                 Vector3 newPos = target.position + new Vector3 (0, relativeHeight, -zDistance);
  14.                 transform.position = Vector3.Lerp (transform.position, newPos, Time.deltaTime * dampSpeed);
  15.         }
  16. }</font>
复制代码


    然后将这个脚本附加给相机:
     

    Target:指向小球物体。
    Relative Height:相机的相对高度
    ZDistace:Z轴相对的距离。
    Damp Speed:物体移动的时候,相机跟随物体的速度。

最后运行如下:

     
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值