2Test/Assets/Script/Player.cs

135 lines
2.8 KiB
C#
Raw Permalink Normal View History

2026-01-22 06:35:21 +00:00
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class Player : MonoBehaviour
{
public float speed;
2026-01-22 10:14:23 +00:00
public GameObject[] weapons;
public bool[] hasWeapons;
2026-01-22 06:35:21 +00:00
float hAxis;
float vAxis;
2026-01-22 10:14:23 +00:00
2026-01-22 06:35:21 +00:00
bool wDown;
bool iDown;
bool jDown;
2026-01-22 10:14:23 +00:00
bool sDown1;
bool sDown2;
2026-01-22 06:35:21 +00:00
bool isJump;
Vector3 moveVec;
Rigidbody rigid;
Animator anim;
GameObject nearObject;
void Awake()
{
rigid = GetComponent<Rigidbody>();
anim = GetComponentInChildren<Animator>();
}
void Update()
{
GetInput();
Move();
Turn();
Jump();
2026-01-22 10:14:23 +00:00
Swap();
Interation();
2026-01-22 06:35:21 +00:00
}
void GetInput()
{
hAxis = Input.GetAxisRaw("Horizontal");
vAxis = Input.GetAxisRaw("Vertical");
wDown = Input.GetButton("Walk");
jDown = Input.GetButtonDown("Jump");
2026-01-22 10:14:23 +00:00
iDown = Input.GetButtonDown("Interation");
sDown1 = Input.GetButtonDown("Swap1");
sDown2 = Input.GetButtonDown("Swap2");
2026-01-22 06:35:21 +00:00
}
void Move()
{
moveVec = new Vector3(hAxis, 0, vAxis).normalized;
if (wDown)
transform.position += moveVec * speed * 2f * Time.deltaTime;
else
transform.position += moveVec * speed * Time.deltaTime;
anim.SetBool("isRun", moveVec != Vector3.zero);
anim.SetBool("isWalk", wDown);
}
void Turn()
{
transform.LookAt(transform.position + moveVec);
}
void Jump()
{
if (jDown && !isJump)
{
rigid.AddForce(Vector3.up * 15, ForceMode.Impulse);
anim.SetBool("isJump", true);
anim.SetTrigger("doJump");
isJump = true;
}
}
2026-01-22 10:14:23 +00:00
void Swap()
{
int weaponIndex = -1;
if (sDown1) weaponIndex = 0;
if (sDown2) weaponIndex = 1;
if ((sDown1 || sDown2) && !isJump)
{
weapons[weaponIndex].SetActive(true);
}
}
void Interation()
{
if(iDown && nearObject != null) {
if(nearObject.tag == "Weapon") {
Item item = nearObject.GetComponent<Item>();
int weaponIndex = item.value;
hasWeapons[weaponIndex] = true;
Destroy(nearObject);
}
}
}
2026-01-22 06:35:21 +00:00
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Floor") {
anim.SetBool("isJump", false);
isJump = false;
}
}
void OnTriggerStay(Collider other)
{
if (other.tag == "Weapon")
nearObject = other.gameObject;
Debug.Log(nearObject.name);
}
void OnTriggerExit(Collider other)
{
if (other.tag == "Weapon")
nearObject = null;
}
}