using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAnimationController : MonoBehaviour
{
Animator anim;
PlayerWeaponManager pw;
int weaponID = 0;
void Start()
{
anim = GetComponent<Animator>();
pw = GetComponent<PlayerWeaponManager>();
}
void Update()
{
WeaponAnimation(pw.curWeaponType);
anim.SetInteger("weapons", weaponID);
}
void WeaponAnimation(string weapon)
{
switch (weapon)
{
case "Nothing":
weaponID = 0;
break;
case "Gun":
weaponID = 1;
break;
case "Pistol":
weaponID = 2;
break;
default:
break;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerWeaponManager : MonoBehaviour
{
public string curWeaponType;
public bool inTrigger = false;
public float throwForce = 800.0f;
public float pickupDelay = 0.1f;
public float friction = 10.0f;
private List<Collider2D> itemColliders; // Список коллайдеров оружия в стэке
void Start()
{
itemColliders = new List<Collider2D>(); // Инициализируем список коллайдеров
}
void Update()
{
WeaponManager();
}
void WeaponManager()
{
if (Input.GetMouseButtonDown(1) && !inTrigger)
{
dropWeapon(curWeaponType);
}
}
public void dropWeapon(string weapon)
{
if (curWeaponType != "Nothing")
{
GameObject weaponPrefab = Resources.Load<GameObject>("Prefabs/Items/" + curWeaponType);
if (weaponPrefab != null)
{
GameObject droppedWeapon = Instantiate(weaponPrefab, transform.position, Quaternion.identity);
Rigidbody2D droppedWeaponRb = droppedWeapon.GetComponent<Rigidbody2D>();
if (droppedWeaponRb != null)
{
Vector2 throwDirection = transform.right.normalized;
droppedWeaponRb.AddForce(throwDirection * throwForce, ForceMode2D.Impulse);
droppedWeaponRb.drag = friction;
}
curWeaponType = "Nothing";
}
else
{
Debug.Log("Weapon prefab not found: " + curWeaponType);
}
}
}
// Метод для добавления коллайдера предмета в стэк
public void AddItemCollider(Collider2D itemCollider)
{
itemColliders.Add(itemCollider);
// Отключаем коллайдер предмета, чтобы его нельзя было сразу подобрать, если на него брошено другое оружие
itemCollider.enabled = false;
}
// Метод для удаления коллайдера предмета из стэка
public void RemoveItemCollider(Collider2D itemCollider)
{
itemColliders.Remove(itemCollider);
// Включаем коллайдер предмета, когда он находится сверху стэка и может быть подобран
itemCollider.enabled = true;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Item
{
public enum WeaponType //Список всего нашего оружия
{
Nothing, //0
Gun, //1
Pistol //2
}
public WeaponType weaponType;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemManager : MonoBehaviour
{
public Item item;
PlayerWeaponManager pw;
private Collider2D itemCollider; // Ссылка на коллайдер предмета
void Start()
{
pw = FindObjectOfType<PlayerWeaponManager>();
itemCollider = GetComponent<Collider2D>(); // Получаем коллайдер предмета
}
private void OnTriggerEnter2D(Collider2D col)
{
// Проверяем, если объект с тегом "Item" входит в триггер предмета, добавляем его коллайдер в список
if (col.CompareTag("Item"))
{
pw.AddItemCollider(col); // Передаем коллайдер предмета в PlayerWeaponManager
}
}
private void OnTriggerExit2D(Collider2D col)
{
if (col.name == "Player")
{
col.GetComponent<PlayerWeaponManager>().inTrigger = false;
}
// Если объект с тегом "Item" выходит из триггера предмета, удаляем его коллайдер из списка
if (col.CompareTag("Item"))
{
pw.RemoveItemCollider(col); // Удаляем коллайдер предмета из PlayerWeaponManager
}
}
private void OnTriggerStay2D(Collider2D col)
{
if (col.name == "Player")
{
col.GetComponent<PlayerWeaponManager>().inTrigger = true;
if (Input.GetMouseButtonDown(1))
{
StartCoroutine("wait");
}
}
}
IEnumerator wait()
{
if (pw.curWeaponType != "Nothing")
{
pw.dropWeapon(pw.curWeaponType); //выкинули оружие
}
yield return new WaitForSeconds(0.05f); //подождали 0,05 сек
pw.curWeaponType = item.weaponType.ToString(); //заменили оружие в руке с выкинутого на поднятый, либо отсутствующий
Destroy(gameObject); //удалили объект, который подобрали
}
}
I only recently (a month ago) started to understand Unity, and decided to make a clone of the Hotline Miami game (or rather a parody). I managed to make a sight, the movement of the camera from the sight, the movement of the character.
That’s just huge problems arose with the selection and drop of weapons.
The mechanics are as follows: There is a weapon on the floor, you approach it and pick it up (the object is destroyed, the variable of the weapon changes to the one that was picked up, the animation is played). This is done by clicking the RIGHT mouse button. If we want to throw an object, then we also press the RIGHT mouse button. If we already have a weapon in our hands, then the current one is dropped, and the lying one is picked up. There are several problems.
- Why the script is not executed immediately from the first right-click (namely selection).
- If two or more items (weapons) are together, then when trying to pick up one is taken, and the second simply disappears.
A lot of attempts have been made to solve this problem. I’ve been tormenting ChatGPT for a very long time, I’ve been practicing Collider2D. It still doesn’t work out.
Scripts are attached:
9194039–1281533–PlayerAnimationController.cs (868 Bytes)
9194039–1281536–PlayerWeaponManager.cs (2.3 KB)
9194039–1281539–Item.cs (298 Bytes)
9194039–1281542–ItemManager.cs (2.25 KB)