I’m new in Unity and C#.And I have some problems. When my character moves using a ‘touchmove’, I used a ‘weapon’ to launch a ‘projectilePrefab’.
However, when I actually touched and moved the character, I had a problem that the “projectilePrefab” was fired too fast.
Help me PLZZZZZZZZ
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour
{
[SerializeField]
private GameObject projectilePrefab;
[SerializeField]
private float attackRate = 0.5f;
public void StartFiring()
{
StartCoroutine("TryAttack");
}
public void StopFiring()
{
StopCoroutine("TryAttack");
}
private IEnumerator TryAttack()
{
while ( true)
{
Instantiate(projectilePrefab, transform.position, Quaternion.identity);
yield return new WaitForSeconds(attackRate);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TouchMove : MonoBehaviour
{
private Vector3 touchPosition;
private Rigidbody2D rb;
private Vector3 direction;
private float moveSpeed = 10f;
private Weapon weapon;
private void Awake()
{
weapon = GetComponent<Weapon>();
}
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
if(Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
touchPosition.z = 0;
direction = (touchPosition - transform.position);
rb.velocity = new Vector2(direction.x, direction.y) * moveSpeed;
weapon.StartFiring();
if (touch.phase == TouchPhase.Ended)
rb.velocity = Vector2.zero;
weapon.StopFiring();
}
}
}
I want to make sure that the launch speed of “projectilePrefab” is fired at 0.5f, which is the launch speed I set.
New contributor
프로필 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.