using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlatformerLayerMaskShoot2D : MonoBehaviour { public float speed = 8; public float jumpForce = 24; [SerializeField] private Transform groundCheck; [SerializeField] private LayerMask groundLayer; public GameObject bullet; public GameObject bulletPos; public float bulletSpeed = 100.0f; Rigidbody2D rb; float horizontal; bool isFacingRight = true; void Start() { rb = GetComponent(); } void Update() { horizontal = Input.GetAxisRaw("Horizontal"); if (Input.GetButtonDown("Jump") == true && IsGrounded() == true) { rb.velocity = new Vector2(rb.velocity.x, jumpForce); } if (Input.GetButtonUp("Jump") == true && rb.velocity.y > 0f) { rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f); } if (Input.GetButtonDown("Fire1")) { Fire(); } Flip(); } void FixedUpdate() { rb.velocity = new Vector2(horizontal * speed, rb.velocity.y); } bool IsGrounded() { return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer); } void Flip() { if (isFacingRight == true && horizontal < 0f || isFacingRight == false && horizontal > 0f) { isFacingRight = !isFacingRight; Vector3 localScale = transform.localScale; localScale.x *= -1; transform.localScale = localScale; } } void Fire() { GameObject tmp; if (isFacingRight == true) { tmp = Instantiate(bullet, bulletPos.transform.position, Quaternion.Euler(0, 0, 0)); tmp.GetComponent().AddForce(new Vector2(10, 0) * bulletSpeed); } else { tmp = Instantiate(bullet, bulletPos.transform.position, Quaternion.Euler(0, 0, 180)); tmp.GetComponent().AddForce(new Vector2(-10, 0) * bulletSpeed); } Destroy(tmp, 5f); } }