PlayerMovement
unknown
csharp
a year ago
13 kB
18
Indexable
using UnityEngine;
using System.Collections;
using System;
public class PlayerMovement : MonoBehaviour
{
//Movement
public float speed;
public float jump;
public float maxJumpTime;
private float jumpTimeCounter;
public float jumpMultiplier;
float moveVelocity;
float inputHorizontal;
float inputVertical;
bool isJumping;
public Transform groundCheck;
public const float groundCheckRadius = 0.5f;
//public LayerMask groundLayer;
private CapsuleCollider2D boxCollider2d;
private Rigidbody2D rigidbody2D;
[SerializeField] AudioSource audioPlayer;
public bool ShouldDoubleJump;
[SerializeField] GameObject meleeCheck;
private Animator anim;
//Grounded Vars
public bool grounded = true;
public bool stoppedJumping;
public bool canDoubleJump;
bool isAttacking = false;
[SerializeField] private LayerMask groundLayerMask;
public AudioClip jumpClip;
public AudioClip atkClip;
private Transform headCheck;
private Health health;
//public float jumpTime;
//private float jumpTimeCounter;
bool facingRight;
[SerializeField]
private bool touchCeiling;
[SerializeField] private GameObject fallDetector;
[SerializeField] private float checkDistance;
private bool touchingWall = false;
private float currentJumpTime;
public bool isCrouching = false;
public bool isOnPlatform;
private bool canJump;
public GameObject projectilePrefab; // Reference to the projectile prefab
public Transform shootPoint; // Point where the projectile will be spawned
public bool canMagicMeat;
public float projectileSpeed = 10f; // Speed of the projectile
public Rigidbody2D platformRb;
private void Start()
{
//jumpTimeCounter = jumpTime;
}
private void Awake()
{
boxCollider2d = transform.GetComponent<CapsuleCollider2D>();
rigidbody2D = transform.GetComponent<Rigidbody2D>();
anim = transform.GetComponent<Animator>();
health = transform.GetComponent<Health>();
audioPlayer = transform.GetComponent<AudioSource>();
meleeCheck.SetActive(false);
facingRight = true;
headCheck = transform.Find("headCheck");
ShouldDoubleJump = true;
}
void Update()
{
if (!health.dead)
{
anim.SetBool("Crouch", false);
inputHorizontal = Input.GetAxisRaw("Horizontal");
inputVertical = Input.GetAxisRaw("Vertical");
//GroundCheckMethod();
//anim.SetBool("Run", false);
//Jumping
grounded = IsTouchingGround();
touchingWall = IsTouchingWall();
// Jump input
if (Input.GetButtonDown("Jump"))
{
if (grounded)
{
ShouldDoubleJump = true;
// Jump only when grounded
isJumping = true;
currentJumpTime = 0f;
audioPlayer.PlayOneShot(jumpClip);
}
else if (touchingWall && !isJumping)
{
// Don't jump from a wall if not grounded
isJumping = true;
currentJumpTime = 0f;
audioPlayer.PlayOneShot(jumpClip);
}
else if (ShouldDoubleJump && canDoubleJump && !isJumping && rigidbody2D.velocity.y > 0)
{
// Double jump only when not already jumping and moving upwards
isJumping = true;
ShouldDoubleJump = false;
currentJumpTime = 0f;
audioPlayer.PlayOneShot(jumpClip);
}
}
// Hold jump to increase height
if (Input.GetButton("Jump") && isJumping)
{
if (currentJumpTime < maxJumpTime)
{
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, jump + (currentJumpTime * jumpMultiplier));
currentJumpTime += Time.deltaTime;
}
else
{
isJumping = false;
}
}
// Release jump button
if (Input.GetButtonUp("Jump"))
{
isJumping = false;
}
//moveVelocity = 0;
//Left Right Movement
if (isOnPlatform)
{
rigidbody2D.velocity = (new Vector2(inputHorizontal * speed + platformRb.velocity.x, rigidbody2D.velocity.y + platformRb.velocity.y));
rigidbody2D.gravityScale = 1;
}
else
{
rigidbody2D.velocity = (new Vector2(inputHorizontal * speed, rigidbody2D.velocity.y));
rigidbody2D.gravityScale = 1;
}
//rigidbody2D.velocity = (new Vector2(inputHorizontal * speed, rigidbody2D.velocity.y));
Console.WriteLine("Input " + inputHorizontal.ToString());
if (inputHorizontal > 0 && !facingRight)
{
//facingRight = true;
Flip();
}
if (inputHorizontal < 0 && facingRight)
{
//facingRight = false;
Flip();
}
if (IsTouchingCeiling())
{
//GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, 0);
jumpTimeCounter = 0;
stoppedJumping = true;
}
if ((Input.GetButtonDown("Fire2")) && !isAttacking)
{
anim.SetTrigger("Attack2");
StartCoroutine(DoAttack());
//isAttacking = true;
//meleeCheck.SetActive(true);
//Invoke("ResetAttack", .5f);
}
//GetComponent<Rigidbody2D>().velocity = new Vector2(moveVelocity, GetComponent<Rigidbody2D>().velocity.y + 0.01f);
bool isWalking = Input.GetAxis("Horizontal") != 0 && grounded && !IsTouchingWall();
anim.SetBool("Run", isWalking);
anim.SetFloat("yVelocity", GetComponent<Rigidbody2D>().velocity.y);
//fall detection
fallDetector.transform.position = new Vector2(transform.position.x, fallDetector.transform.position.y);
if (rigidbody2D.transform.position.y < fallDetector.transform.position.y)
{
health.Instakill();
}
//idle
if (!grounded && !touchingWall)
{
anim.SetBool("grounded", false);
}
else
{
anim.SetBool("grounded", true);
}
}
}
void Flip()
{
// Multiply the player's x local scale by -1
Vector3 currentScale = transform.localScale;
currentScale.x *= -1;
transform.localScale = currentScale;
// Switch the way the player is labelled as facing
facingRight = !facingRight;
}
private void FixedUpdate()
{
}
/*void ResetAttack()
{
isAttacking = false;
meleeCheck.SetActive(false);
}*/
IEnumerator DoAttack()
{
isAttacking = true;
meleeCheck.SetActive(true);
audioPlayer.PlayOneShot(atkClip);
if (canMagicMeat)
{
ShootProjectile();
}
yield return new WaitForSeconds(0.3f);
isAttacking = false;
meleeCheck.SetActive(false);
//anim.SetBool("Attack", false);
}
//Check if Grounded
void OnTriggerEnter2D()
{
//grounded = true;
}
void OnTriggerExit2D()
{
//grounded = false;
}
bool IsTouchingCeiling()
{
// Calculate an offset based on the collider's size
float yOffset = boxCollider2d.bounds.size.y / 2f;
// Adjust the starting position of the ray to the top-center of the player
Vector2 rayStart = new Vector2(transform.position.x, transform.position.y + yOffset);
// Cast rays from the left and right edges of the player's collider
RaycastHit2D hitLeft = Physics2D.Raycast(rayStart - new Vector2(boxCollider2d.bounds.size.x / 2f, 0f), Vector2.up, 0.1f, groundLayerMask);
RaycastHit2D hitRight = Physics2D.Raycast(rayStart + new Vector2(boxCollider2d.bounds.size.x / 2f, 0f), Vector2.up, 0.1f, groundLayerMask);
// If either ray hits something, return true
return hitLeft.collider != null || hitRight.collider != null;
}
private bool IsTouchingGround()
{
float yOffset = boxCollider2d.bounds.size.y / 2f;
float xOffset = boxCollider2d.bounds.size.x / 2f;
float rayLength = 0.1f; // Adjust the ray length as needed
Vector2 bottomCenter = new Vector2(transform.position.x, transform.position.y - yOffset);
// Perform a box cast straight down from the bottom center of the player
RaycastHit2D hit = Physics2D.BoxCast(bottomCenter, new Vector2(xOffset * 2, rayLength), 0f, Vector2.down, rayLength, groundLayerMask);
// Visualize the box cast in the Scene view
Debug.DrawRay(bottomCenter, Vector2.down * rayLength, Color.red);
// Return true if the box cast hits the ground
if (hit.collider != null)
{
// Add a condition to allow jumping through one-way platforms
if (hit.collider.gameObject.layer == groundLayerMask.value)
{
// Check if the player is moving upwards (jumping)
if (rigidbody2D.velocity.y > 0)
{
ShouldDoubleJump = true;
// Allow jumping through one-way platforms
return true;
}
}
}
anim.SetBool("grounded", hit.collider != null);
if(hit.collider != null)
{
ShouldDoubleJump = true;
}
// Return true if the box cast hits the ground
return hit.collider != null;
}
private bool IsTouchingWall()
{
float xOffset = boxCollider2d.bounds.size.x / 2f;
float yOffset = boxCollider2d.bounds.size.y / 2f;
Vector2 sideLeft = new Vector2(transform.position.x - xOffset, transform.position.y);
Vector2 sideRight = new Vector2(transform.position.x + xOffset, transform.position.y);
// Cast rays horizontally from the left and right edges of the player's collider
bool wallLeft = Physics2D.Raycast(sideLeft, Vector2.left, 0.1f, groundLayerMask);
bool wallRight = Physics2D.Raycast(sideRight, Vector2.right, 0.1f, groundLayerMask);
// Visualize the rays in the Scene view
Debug.DrawRay(sideLeft, Vector2.left * 0.1f, Color.blue);
Debug.DrawRay(sideRight, Vector2.right * 0.1f, Color.blue);
// Return true only if both side rays hit a wall
return wallLeft && wallRight;
}
void ShootProjectile()
{
if (projectilePrefab != null && shootPoint != null)
{
// Instantiate the projectile at the shootPoint position and rotation
GameObject newProjectile = Instantiate(projectilePrefab.gameObject, shootPoint.position, shootPoint.rotation);
PlayerProjectle playerProjectle = newProjectile.GetComponent<PlayerProjectle>();
Debug.Log("Tir");
// Calculate the direction of the projectile
Vector2 shootDirection = facingRight ? Vector2.right : Vector2.left;
playerProjectle.facingRight = facingRight? true: false;
// Access the projectile's Rigidbody2D component
Rigidbody2D projectileRigidbody = playerProjectle.GetComponent<Rigidbody2D>();
if (projectileRigidbody != null)
{
// Apply force to the projectile in the shoot direction
//playerProjectle.maxDistance += Math.Abs(rigidbody2D.velocity.x/2);
projectileRigidbody.velocity = shootDirection * playerProjectle.speed + rigidbody2D.velocity;
Debug.Log("Vitesse projectile:" + projectileRigidbody.velocity);
}
}
}
}Editor is loading...
Leave a Comment