《Unity3D-魚的方向 魚的游動 控制代碼》


public class fishGame : MonoBehaviour {

enum FishDir //設置朝向的枚舉
{
left,
right
}
FishDir dir; //申明一個方向控制魚
Vector3 target; //申明目標變量
public float speed = 2; //設置魚的速度

// Use this for initialization
void Start () {
float random = Random.value; //隨機設置魚的方向
while (random==0.5f) //循環判斷random直到整個數字不等於0.5
{
random = Random.value;
}
if (random>0.5f) //如果隨機數大於0.5的情況和小於的情況
{
dir = FishDir.left;
}
else
{
dir = FishDir.right;
}
ChangeDir(); //調用改變方向的方法
SetTarget(); //調用設置目標的方法
}

// Update is called once per frame
void Update () {
Move();
}

void ChangeDir()
{
Vector3 scale = transform.localScale; //設置scale變量
if (dir == FishDir.left) //判斷如果魚兒的方向朝左時設置魚兒的scale=1
{
scale.x = 1;
}
else
{
scale.x = -1;
}
transform.localScale = scale; //重新賦值
}

void SetTarget() //設置目標的方法
{
float x = dir == FishDir.left ? -0.2f : 1.2f; //使用判斷左右的方法為x的值賦值0或者1;
Vector3 viewPoint = new Vector3(x, Random.value,-Camera.main.transform.position.z); //生成一個點的位置坐標信息 不過他的這些信息只調用一次
target = Camera.main.ViewportToWorldPoint(viewPoint); //在世界坐標系中去實例化一個目標點
}

void Move() //設置移動的方法
{
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
if (Vector3.Distance(transform.position, target) == 0) //判斷魚是否到達邊界位置
{
dir = dir == FishDir.left ? FishDir.right : FishDir.left; //控制魚取得相反的方向
ChangeDir();
SetTarget();
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM