Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class PlayerCtrl : MonoBehaviour
- {
- [Tooltip("this is an positive integer which speeds up the player movement")]
- public int speedBoost; // set this to 5
- public float jumpSpeed; // set this to 600
- public bool isGrounded;
- public Transform feet;
- public float feetRadius;
- public LayerMask whatIsGround;
- public Transform leftBulletSpawnPos, rightBulletSpawnPos;
- public GameObject leftBullet, rightBullet;
- Rigidbody2D rb;
- SpriteRenderer sr;
- Animator anim;
- bool isJumping;
- bool leftPressed, rightPressed;
- void Start()
- {
- rb = GetComponent<Rigidbody2D>();
- sr = GetComponent<SpriteRenderer>();
- anim = GetComponent<Animator>();
- }
- void Update()
- {
- isGrounded = Physics2D.OverlapCircle(feet.position, feetRadius, whatIsGround);
- float playerSpeed = Input.GetAxisRaw("Horizontal"); // value will be 1, -1 or 0
- playerSpeed *= speedBoost; // playerSpeed = playerSpeed * speedBoost
- if (playerSpeed != 0)
- MoveHorizontal(playerSpeed);
- else
- StopMoving();
- if (Input.GetButtonDown("Jump"))
- Jump();
- if (Input.GetButtonDown("Fire1"))
- {
- FireBullets();
- }
- ShowFalling();
- if (leftPressed)
- MoveHorizontal(-speedBoost);
- if (rightPressed)
- MoveHorizontal(speedBoost);
- }
- void OnDrawGizmos()
- {
- Gizmos.DrawWireSphere(feet.position, feetRadius);
- }
- void MoveHorizontal(float playerSpeed)
- {
- rb.velocity = new Vector2(playerSpeed, rb.velocity.y);
- if (playerSpeed < 0)
- sr.flipX = true;
- else if (playerSpeed > 0)
- sr.flipX = false;
- if (!isJumping)
- anim.SetInteger("State", 1);
- }
- void StopMoving()
- {
- rb.velocity = new Vector2(0, rb.velocity.y);
- if (!isJumping)
- anim.SetInteger("State", 0);
- }
- void ShowFalling()
- {
- if (rb.velocity.y < 0)
- {
- anim.SetInteger("State", 3);
- }
- }
- void Jump()
- {
- if (isGrounded)
- {
- isJumping = true;
- rb.AddForce(new Vector2(0, jumpSpeed)); //simply make the player jump in the y axis or upwards
- anim.SetInteger("State", 2);
- }
- }
- void FireBullets()
- {
- // makes the player fire bullets in the left direction
- if (sr.flipX)
- {
- Instantiate(leftBullet, leftBulletSpawnPos.position, Quaternion.identity);
- }
- // makes the player fire bullets in the right direction
- if (!sr.flipX)
- {
- Instantiate(rightBullet, rightBulletSpawnPos.position, Quaternion.identity);
- }
- }
- public void mobileMoveLeft()
- {
- leftPressed = true
- }
- public void mobileMoveright()
- {
- rightPressed = true
- }
- public void MobileStop()
- {
- leftPressed = false
- rightPressed = false
- StopMoving();
- }
- void OnCollisionEnter2D(Collision2D other)
- {
- if (other.gameObject.CompareTag("Ground"))
- {
- isJumping = false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement