Answer the question
In order to leave comments, you need to log in
The object appears elsewhere. What to do?
Pay attention to the LetGo coroutine. The object appears elsewhere.
using System.Collections;
using UnityEngine;
public class ArrowController : MonoBehaviour
{
public Rigidbody2D ArrowRb;
public GameObject _arrow;
public GameObject bow;
bool _isPressed;
public bool isShot;
public float LounchForce;
public float speed;
public float MaxDistance;
float ArrowDistance;
Vector2 StartPoint;
Vector2 EndPoint;
public GameObject ArrowPrefab;
public Transform SpawnPoint;
void Start()
{
ArrowRb.isKinematic = true;
}
void FixedUpdate()
{
GetButton();
isPressed();
ArrowAngle();
}
void GetButton()
{
if (isShot == false)
{
if (Input.GetButtonDown("Fire1"))
{
StartPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
_isPressed = true;
}
if (Input.GetButtonUp("Fire1"))
{
_isPressed = false;
isShot = true;
ArrowRb.isKinematic = false;
ArrowRb.AddRelativeForce(_arrow.transform.right * LounchForce * ArrowDistance, ForceMode2D.Impulse);
StartCoroutine(LetGo());
}
}
}
void isPressed()
{
ArrowDistance = Vector2.Distance(_arrow.transform.position, bow.transform.position);
if (_isPressed)
{
if (ArrowDistance > MaxDistance)
{
ArrowDistance = MaxDistance - 0.03f;
}
else
{
EndPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 _Direction = StartPoint - EndPoint;
_arrow.transform.position -= _Direction * 0.005f;
}
}
}
void ArrowAngle()
{
Vector2 Vec = ArrowRb.velocity;
var angle = Mathf.Atan2(Vec.y, Vec.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
void OnCollisionEnter2D(Collision2D collision)
{
ArrowRb.velocity = Vector2.zero;
ArrowRb.isKinematic = true;
}
IEnumerator LetGo()
{
yield return new WaitForSeconds(0.5f);
GameObject newArrow = Instantiate(ArrowPrefab, SpawnPoint.position, SpawnPoint.rotation);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question