2075 / Unity / 2D / Гравець / Unity 3D Вид зверху + вліво-вправо + постріл
PlayerFlipShoot2D |
- Player і Bullet мають мати Rigidbody2D
- bulletPos – всередині playerImg (справа)
- Edit -> Project Settings… -> Input Manager – змінити клавіши
- Якщо герой чи куля дивляться не вправо, то їх покласти в пустий об'єкт та розгорнути
- Якщо пуля проходить крізь стіни Rigidbody2D -> Collision Detection = Continuous
public GameObject bullet; public GameObject bulletPos; public float playerSpeed = 6.0f; public float bulletSpeed = 400.0f; Rigidbody2D rb; Vector2 movement; bool isFacingRight = true; void Start() { rb = GetComponent<Rigidbody2D>(); } void Update() { movement.x = Input.GetAxisRaw("Horizontal"); movement.y = Input.GetAxisRaw("Vertical"); if (movement.x > 0 && movement.y == 0) { Flip(); } else if (movement.x < 0 && movement.y == 0) { Flip(); } if (Input.GetButtonDown("Fire1")) { GameObject tmp = Instantiate(bullet, bulletPos.transform.position, Quaternion.Euler(0, 0, 0)); Rigidbody2D tmpRB = tmp.GetComponent<Rigidbody2D>(); Destroy(tmp, 5f); if (isFacingRight == true) { tmpRB.AddForce(new Vector2(5, 0) * bulletSpeed); } else { tmp.transform.rotation = Quaternion.Euler(0, 0, 180); tmpRB.AddForce(new Vector2(-5, 0) * bulletSpeed); } } } void FixedUpdate() { rb.MovePosition(rb.position + movement * playerSpeed * 0.02f); } void Flip() { if (isFacingRight == true && movement.x < 0 || isFacingRight == false && movement.x > 0) { isFacingRight = !isFacingRight; Vector3 localScale = transform.localScale; localScale.x *= -1; transform.localScale = localScale; } }