Unity 2D Вид зверху + обертання + постріл

  • playerImage – має знаходитися всередині Player
  • Player і Bullet мають мати Rigidbody2D
  • Якщо герой чи куля дивляться не вправо, то їх покласти в пустий об’єкт та розгорнути

 

public GameObject playerImg;
public GameObject bullet;
public GameObject bulletPos;
public float playerSpeed = 6.0f;
public float bulletSpeed = 400.0f;
Rigidbody2D rb;
Vector2 movement;

void Start()
{
  rb = GetComponent<Rigidbody2D>();
}

void Update()
{
  movement.x = Input.GetAxisRaw("Horizontal");
  movement.y = Input.GetAxisRaw("Vertical");

  if (movement.x == 0 && movement.y > 0)
  {
    playerImg.transform.rotation = Quaternion.Euler(0, 0, 90);
  }
  else if (movement.x == 0 && movement.y < 0)
  {
    playerImg.transform.rotation = Quaternion.Euler(0, 0, -90);
  }
  else if (movement.x > 0 && movement.y == 0)
  {
    playerImg.transform.rotation = Quaternion.Euler(0, 0, 0);
  }
  else if (movement.x < 0 && movement.y == 0)
  {
    playerImg.transform.rotation = Quaternion.Euler(0, 0, 180);
  }

  if (Input.GetKeyDown(KeyCode.Space))
  {
    GameObject go = Instantiate(bullet, bulletPos.transform.position, Quaternion.Euler(0, 0, 0));
    go.transform.rotation = Quaternion.Euler(0, 0, playerImg.transform.rotation.eulerAngles.z);
    Rigidbody2D goRb = go.GetComponent<Rigidbody2D>();
    Destroy(go, 5f);

    if (playerImg.transform.rotation.eulerAngles.z == 0)
    {
      goRb.AddForce(new Vector2(5, 0) * bulletSpeed);
    }
    else if (playerImg.transform.rotation.eulerAngles.z == 180)
    {
      goRb.AddForce(new Vector2(-5, 0) * bulletSpeed);
    }
    else if (playerImg.transform.rotation.eulerAngles.z == 90)
    {
      goRb.AddForce(new Vector2(0, 5) * bulletSpeed);
    }
    else if (playerImg.transform.rotation.eulerAngles.z == 270)
    {
      goRb.AddForce(new Vector2(0, -5) * bulletSpeed);
    }
  }
}

void FixedUpdate()
{
  rb.MovePosition(rb.position + movement * playerSpeed * 0.02f);
}