2012-03-23 67 views
1

我正在爲一個遊戲編程課而設計一個項目,而且我無法將簡單的2D人工智能向左右移動。我可以讓他向左移動並將他限制在屏幕上,但不能向右移動。我一直在努力,並希望得到任何幫助。感謝您的時間。統一人工智能運動C#

代碼:

using UnityEngine; 
using System.Collections; 



public class ThiefMove : MonoBehaviour { 

    public int moveSpeed = 140; //per second 
    public int computerDirection; 
    public Transform diamond; 
    Vector3 moveDirection = Vector3.zero; 
    Vector3 newPosition = Vector3.zero; 

    // Use this for initialization 

void Start() 

{ 
} 

void Update() 

{ 

     Vector3 newPosition = new Vector3(-1,0,0) * (moveSpeed * Time.deltaTime); 
     newPosition = transform.position + newPosition; 
     newPosition.x = Mathf.Clamp(newPosition.x, -101, 126); 
     transform.position = newPosition; 

     if(newPosition.x == -101) 

     { 

     Vector3 rightPosition = new Vector3(1,0,0) * (moveSpeed * Time.deltaTime); 
     rightPosition = transform.position + rightPosition; 
     newPosition.x = Mathf.Clamp(newPosition.x, -101, 126); 
     transform.position = rightPosition; 

     } 



     if(newPosition.x == 126) 

     { 

     Vector3 leftDirection = Vector3.left * (moveSpeed * Time.deltaTime); 
     leftDirection = transform.position + leftDirection; 
     newPosition.x = Mathf.Clamp(newPosition.x, -101, 126); 
     transform.position = leftDirection; 
     } 

if (transform.gameObject) 

    { 

    diamond = Instantiate(diamond, newPosition, transform.rotation) as Transform; 

    } 

    } 

} 
+0

以上代碼的哪部分移動了小偷左側 – 2012-03-23 03:25:24

+3

您應該抽象並封裝所有角色的行爲,以便您的代碼更易讀易懂。這將最終幫助你解決問題,它更容易說:character.MoveRight(像素:101);比:newPosition.x = MathfClamp(newPosition.x,-101,126);如果只需要記住簡單的單詞,而不是複雜的API指令,則您的大腦可以「解決更多」問題。 – 2012-03-23 05:32:07

回答

0

我不知道你要完成的任務,但這裏做的更好的辦法:

public int moveSpeed = 140; //per second 
public int computerDirection; 
public Transform diamond; 
Vector3 moveDirection = new Vector3(-1, 0, 0); 
bool movingLeft = false; 

void Update() 
{ 
    // If thief is moving to the right and its position is -101 
    // set movingLeft to true and change direction 
    if(!movingLeft && transform.localPosition.x <= -101) 
    { 
     moveDirection = new Vector3(1,0,0); 
     movingLeft = true; 
    } 

    // If thief is moving to the left and its position is 126 
    // set movingLeft to false and change direction 
    if(movingLeft && transform.localPosition.x >= 126) 
    { 
     moveDirection = new Vector3(-1,0,0); 
     movingLeft = false; 
    } 

    transform.Translate(moveSpeed * Time.deltaTime * moveDirection); 

} 

不是最好的方式做,但你這個想法。當玩家向右移動時,您應該選擇正確的位置,左邊的位置應該相同。