在场景中创建一个小球,这个小球就是平衡游戏的主角,让小球滚动来,通过控制滚动的方向来实现平衡.
搭建场景如下:
给小球添加刚体和Sphere Collider
:
然后简单粗暴上脚本:挂载到Ball上
using UnityEngine;
using System.Collections;
public class BallMovement : MonoBehaviour { // attach this script to ball
// Use this for initialization, change values in Inspector for tweaking
public float normalForce = 200.0f;
public float boostForce = 15000.0f;
public float maxSpeed = 50.0f;
private GameObject ball;
private bool boostActive;
private Vector3 ballStartPosition;
private Vector3 ballDirection, ballForward;
private Vector3 ballPosition1, ballPosition2; // used to determine the effective movement of the ball between updates
private float directionHorizontal, directionVertical;
private float distanceToGround; // used to check if ball is on ground
void Start () {
distanceToGround = GetComponent<Collider>().bounds.extents.y + 0.1f; // 初始化并增加安全系数以解释不平整的地面
ballStartPosition = transform.position; // 存储启动位置在水平复位的情况下
ballPosition1 = transform.position; //初始化运动向量,用来计算方向向量
ball = GameObject.FindGameObjectWithTag(Tags.ball);
if (ball == null) {Debug.LogError ("<color=blue>Marble Kit error:</color>: There needs exactly one object with the tag 'Ball' in the scene");}
}
void Update () // 在player上创建运动矢量
{
directionHorizontal = Input.GetAxis("Horizontal");
directionVertical = Input.GetAxis("Vertical");
ballDirection.x = directionHorizontal;
ballDirection.z = directionVertical;
ballDirection.y = 0;
boostActive = Input.GetKey("space"); // 添加一个加速的判断
}
void FixedUpdate() // physics is executed during FixedUpdate, so we use this too
{
GetComponent<Rigidbody>().AddForce(ballDirection * normalForce * Time.deltaTime); // add force/speed to ball in vector direction
ballDirection = Vector3.zero; // 然后重置 否则力将持续不断的应用
ballPosition2 = transform.position; // create a forward vector = direction the ball moves effectively between updates. I found the .direction method not to yield good results
ballForward = ballPosition2 - ballPosition1;//创建一个正向向量=球在更新之间有效移动的方向。我发现,不会产生好结果的方向的方法
if (boostActive && BallIsGrounded()) // 满足点击键盘空格键的布尔值,和在地面上
{
ballForward.y = 0;
GetComponent<Rigidbody>().AddForce(ballForward * boostForce * Time.deltaTime);
}
if (GetComponent<Rigidbody>().velocity.magnitude > maxSpeed) // 限制最大速度
{
GetComponent<Rigidbody>().velocity = GetComponent<Rigidbody>().velocity.normalized * maxSpeed;
}
ballPosition2 = ballPosition1; // 更改矢量以允许下一个球方向检查。
ballPosition1 = transform.position;
}
public void ResetBallPosition()
{
this.transform.position = ballStartPosition;
this.GetComponent<Rigidbody>().velocity = Vector3.zero;
ball.SetActive(true);
}
bool BallIsGrounded() // checks if ball is on ground
{
return Physics.Raycast(transform.position, -Vector3.up, distanceToGround);
}
}
应用实例:平衡小球
平衡小球Demo下载:点击打开链接
http://download.csdn.net/detail/gaoheshun/9899079