Как сделать разброс пуль в Unity 2D?
Нужен разброс пуль в Top down shooter. Снизу код который сейчас. Как я думаю, нужно просто добавить градус к уже готовому градусу пули, но как? На видео показал как выглядит стрельба сейчас. переменная Scatter должна обозначать силу разброса, типо - градус пули + Random.Range(-Scatter, Scatter);
Видео - https://youtu.be/65QBea-_6u4
Мой вариант не работает/работает странно:
private void Shoot()
{
Quaternion Angle = transform.parent.parent.rotation;
Angle.z += Random.Range(-Scatter, Scatter);
GameObject Bullet = Instantiate(BulletPrefab, ShootPos.position, Angle);
Bullet.GetComponent<Rigidbody2D>().velocity = transform.parent.parent.right * BulletForce *
Time.fixedDeltaTime;
}
Код:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pistol : MonoBehaviour
{
public GameObject BulletPrefab;
public Transform ShootPos;
public float BulletForce;
public int Scatter;
private void FixedUpdate()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
Shoot();
}
}
private void Shoot()
{
GameObject Bullet = Instantiate(BulletPrefab, ShootPos.position, Angle);
Bullet.GetComponent().velocity = transform.parent.parent.right * BulletForce * Time.fixedDeltaTime;
}
}
Ответы (1 шт):
Автор решения: Yaroslav
→ Ссылка
[DisallowMultipleComponent]
// логичней что спускает курок персонаж...
public class Player : MonoBehaviour () {
[SerializeField] private Gun _gun;
// почему FixedUpdate? как это связано с апдейтом физики?
private void Update () {
if (Input.GetKeyDown(KeyCode.Mouse0) && _gun != null)
_gun.Shoot();
}
}
[DisallowMultipleComponent]
public class Gun : MonoBehaviour {
// тут нет полей которые должны быть public
[SerializeField] private float _scatter;
[Space]
[SerializeField] private Transform _firePoint;
[SerializeField] private Bullet _bulletTeplate;
public void Shoot () {
if (_bulletTeplate != null) {
// привычный нам угол в градумах, это углы эйлера, а не Quaternion
Vector3 Angle = _firePoint.eulerAngles;
Angle.z += Random.Range(-_scatter, _scatter);
Instantiate(_bulletTeplate.gameObject, _firePoint.position, Quaternion.Euler(Angle));
}
}
}
[DisallowMultipleComponent]
[RequireComponent(typeof(Rigidbody2D))]
public class Bullet : MonoBehaviour {
[SerializeField] private float _speed;
private void Start () {
Rigidbody2D Body = GetComponent<Rigidbody2D>();
// зачем ты умножаешь скорость на дельту времени?
// .forward зависит от поворота firePoint и самой пули
Body.velocity = transform.forward*_speed;
}
}