2017-12-05 1 views
0

프로그래밍에 익숙하지는 않지만 C#을 처음 사용합니다. 나는 Python, Java, HTML로 경험이있다. 내 게임은 2D입니다. 내 캐릭터가 현재 적을 만져서 죽이는 게임이 있습니다. 이제 적을 죽이기 위해 총알을 쏘는 코드를 추가했습니다. 스페이스 바를 누르면 총알이 발사되기를 바랄뿐입니다. 캐릭터는 어느 방향으로나 총알을 맞았습니다. 교수님이 저에게 준 Javascript 예제에서 코드를 가져 와서 C#으로 변환했습니다. Unity는 더 이상 자바 스크립트를 지원하지 않습니다. 그가 내게 준 예제 코드는 기본적으로 로켓을 총알처럼 쏘아 발사 한 것입니다 (마우스를 클릭하면 총알이 발사 됨). 적을 없애기 위해 발사 한 것이지만, 그 예에서 로켓은 움직이지 않습니다. 내 게임에서 캐릭터가 움직이므로 총알은 캐릭터의 위치를 ​​얻어야합니다. 캐릭터의 위치를 ​​파악하고 총알을 정확히 쏠 수있는 올바른 코드는 무엇입니까?글 머리 기호를 올바르게 촬영하려면 유니티 캐릭터에 필요한 코드는 무엇입니까?

나는 내 게임을 현재 코드로 테스트했다. 총알이 아무 곳에도 뱉어 내지 않고 있습니다. (내 배경 벽지의 아래쪽에서부터 아래쪽의 중간에 가볍게 두드려서 벽지 아래까지). 캐릭터로부터조차 ... 또한 Unity에서 Bullet 카테고리에 Hit 클래스 스크립트를 추가했습니다.

전체 카메라 컨트롤러 (여기에 전혀 문제)

using UnityEngine; 
using System.Collections; 

public class CompleteCameraController : MonoBehaviour { 

    public GameObject player;  //Public variable to store a reference to the player game object 


    private Vector3 offset;   //Private variable to store the offset distance between the player and camera 

    // Use this for initialization 
    void Start() 
    { 
     //Calculate and store the offset value by getting the distance between the player's position and camera's position. 
     offset = transform.position - player.transform.position; 
    } 

    // LateUpdate is called after Update each frame 
    void LateUpdate() 
    { 
     // Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance. 
     transform.position = player.transform.position + offset; 
    } 
} 

전체 플레이어 컨트롤 클래스 (당신이 "BULLET 코드"를 말하는 코드의 주석을 읽는다면, 즉 내가에 배치 한 새로운 코드의 총알을위한 게임.

using UnityEngine; 
using System.Collections; 

//Adding this allows us to access members of the UI namespace including Text. 
using UnityEngine.UI; 

public class CompletePlayerController : MonoBehaviour 
{ 

    public float speed;    //Floating point variable to store the player's movement speed. 
    public Text countText;   //Store a reference to the UI Text component which will display the number of pickups collected. 
    public Text winText;   //Store a reference to the UI Text component which will display the 'You win' message. 

    private Rigidbody2D rb2d;  //Store a reference to the Rigidbody2D component required to use 2D Physics. 
    private int count;    //Integer to store the number of pickups collected so far. 
    Rigidbody2D bullet; 
    float speed2 = 30f; //BULLET CODE 



    // Use this for initialization 
    void Start() 
    { 
     //Get and store a reference to the Rigidbody2D component so that we can access it. 
     rb2d = GetComponent<Rigidbody2D>(); 

     //Initialize count to zero. 
     count = 0; 

     //Initialze winText to a blank string since we haven't won yet at beginning. 
     winText.text = ""; 

     //Call our SetCountText function which will update the text with the current value for count. 
     SetCountText(); 
    } 

    //FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here. 
    void FixedUpdate() 
    { 
     //Store the current horizontal input in the float moveHorizontal. 
     float moveHorizontal = Input.GetAxis ("Horizontal"); 

     //Store the current vertical input in the float moveVertical. 
     float moveVertical = Input.GetAxis ("Vertical"); 

     Rigidbody2D bulletInstance; //BULLET CODE 

     //Use the two store floats to create a new Vector2 variable movement. 
     Vector2 movement = new Vector2 (moveHorizontal, moveVertical); 

     //Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player. 
     rb2d.AddForce (movement * speed); 

     if(Input.GetKeyDown(KeyCode.Space)&& Hit.hit == false) //BULLET CODE IN HERE 
     { 
      // ... instantiate the bullet facing right and set it's velocity to the right. 
      bulletInstance = Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0,0,0))); 
      bulletInstance.velocity = new Vector2(speed2, 0); 
      bulletInstance.name = "Bullet"; 
     } 







    } 




    //OnTriggerEnter2D is called whenever this object overlaps with a trigger collider. 
    void OnTriggerEnter2D(Collider2D other) 
    { 
     //Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is... 
     if (other.gameObject.CompareTag ("PickUp")) 
     { 
      //... then set the other object we just collided with to inactive. 
      other.gameObject.SetActive(false); 

      transform.localScale += new Vector3(0.1f, 0.1f, 0); 

      //Add one to the current value of our count variable. 
      count = count + 1; 

      //Update the currently displayed count by calling the SetCountText function. 
      SetCountText(); 
     } 


    } 

    //This function updates the text displaying the number of objects we've collected and displays our victory message if we've collected all of them. 
    void SetCountText() 
    { 
     //Set the text property of our our countText object to "Count: " followed by the number stored in our count variable. 
     countText.text = "Count: " + count.ToString(); 

     //Check if we've collected all 12 pickups. If we have... 
     if (count >= 12) 
      //... then set the text property of our winText object to "You win!" 
      winText.text = "You win!"; 
    } 
} 

히트 코드.이 클래스의 모든 코드는 총알을 위해 만들어졌다.

using UnityEngine; 
using System.Collections; 

public class Hit : MonoBehaviour 
{ 


    GameObject[] gameObjects; 
    public static bool hit = false; 

    void Removal() 
    { 

    gameObjects = GameObject.FindGameObjectsWithTag("Bullet"); 

    for(var i= 0 ; i < gameObjects.Length ; i ++) 
     Destroy(gameObjects[i]); 
    } 

    void OnCollisionEnter2D (Collision2D other ) 
    { 
     if(other.gameObject.name=="Bullet") 
     { 
      Removal(); 
      Destroy(gameObject); 
      hit = true; 

     } 
    } 
} 
+0

게임이 3D가 아닌 2D임을 지정할 수 있습니다. –

답변

0

아마도이 문제는 플레이어의 부모 변환과 관련이 있습니다. 당신은 총알이 오른쪽에 부모가 있는지 확인하기 위해이 같은 일을 시도 할 수 :

bulletInstance = Instantiate(bullet); 
bulletInstance.transform.parent = transform.parent; 
bulletInstance.transform.position = transform.position; 
bulletInstance.velocity = new Vector2(speed2, 0); 
bulletInstance.name = "Bullet"; 

을 그게 플레이어의 사각형은 앵커 피봇이 어디에 있는지보기 위해 변환 확인하는 가치가있을 수 있습니다 작동하지 않는 경우. 아마도 플레이어의 실제 "위치"좌표는 자신이 생각하는 위치가 아닙니다.

우주 사수 자습서를 해 보셨습니까? 그것에는 segment about shooting bullets가 있습니다.

+0

코드를 코드로 변경했지만 여전히 작동하지 않지만, 지금 당장 귀하의 의견에있는 링크를 사용해 보겠습니다. – potanta

+0

웹 사이트의 코드를 사용해 보았는데 프로젝트에서 작동하지 않습니다. 나는 지금 가지고있는 코드를 고수하고 그것을 고쳐야한다. – potanta

+0

자습서의 내용을 이해하면 지금 가지고있는 코드를 수정할 수 있습니다. –

1

작성한 코드에 몇 가지 문제가 있습니다. @Kyle Delaney가 제안한대로 Unity 웹 사이트를 확인하고 이동하기 전에 여러 자습서를 검토하는 것이 좋습니다. 아래에서 문제를 해결하는 데 도움이 될 수있는 몇 가지 문제를 강조했지만, 이러한 문제를 피하기 위해 처음부터 접근 방식을 변경하면 실제로 이점을 얻을 수 있습니다. 아래를 참조하십시오.

변경 : A의

if (Input.GetKeyDown(KeyCode.Space)) //Shoot bullet 
{ 
    // ... instantiate the bullet facing right and set it's velocity to the right. 
    Rigidbody2D bulletRB = Instantiate(bullet, transform.position, transform.rotation); 
    bulletRB.AddForce(new Vector2(speed2,0), ForceMode2D.Impulse); 
} 

을 사용하면 플레이어 컨트롤러 클래스에서

>는 관리자에서 직접 설정할 수 있도록 오프셋 공개하지 왜 카메라 컨트롤러 클래스에서

, 클릭하면 총알 조립식을 인스턴스화하고 플레이어의 위치와 회전을 복사하도록 변형을 설정합니다. 그런 다음 오른쪽에 힘을 추가합니다. 강체를 사용하여 수동으로 속도를 설정하지 않아야합니다. 이로 인해 원하지 않는 동작이 발생할 수 있습니다. 대신에 Addforce/addTorque 메소드를 사용하십시오. ForceMode는 질량을 무시하고 속도를 설정한다고 말합니다.

그런 다음 Hit 클래스를 삭제하고이 Bullet 클래스로 바꾸십시오.이 Bullet 클래스는 글 머리 프리 프레임으로 드래그합니다. 당신의 선수는 총알에 대한 체크를 담당해서는 안됩니다. 그건 총알의 일이야. 플레이어가 총알을 발사하면 총알이 총알을 발사합니다. 이것은 총알이 무엇인가를 치는지 여부를 확인합니다. 그렇다면 파괴합니다. 원한다면 더 복잡하게 만들 수 있습니다. 총알이 충돌을 확인하는 레이어를 결정하기 위해 레이어를 사용하는 것이 좋습니다. 아마 총알이 당신의 지형을 파괴하는 것을 원하지 않을 것입니다. 그리고 총알이 플레이어 자체를 파괴하는 것을 원하지 않는 것은 분명합니다! 당신의 조립식 총알이 이미 "총알"이름을 지정해야하기 때문에

public class Bullet : MonoBehaviour 
{ 

    private void OnCollisionEnter2D(Collision2D collision) 
    { 
     Destroy(collision.gameObject); 
     Destroy(this.gameObject); 
    } 

} 

또한 당신은 총알의 이름을 설정할 필요가 없습니다.

나는 이것이 올바른 방향으로 시작되기를 바랍니다. 그러나 코드를 기반으로, 어떤 프로젝트를 계속하기 전에 자습서를 통해 작업 할 것을 적극 권장합니다. 그것들을 만드는 화합 스태프들은 매우 유용하며 튜토리얼은 정말 간단하지만 실제로는 복잡해지기 때문에 실제로 톤을 배우러 와야합니다!

관련 문제