Jurajkeee
@Jurajkeee
Baby Developer

Как поменять направление пули?

Недавно начал работать в юнити. Делаю простой проект. В процессе разработки возник вопрос как поменять направление пули? Она всегда летит вправо. Перепробовал много разных функций и результат один и тотже
using UnityEngine;
using System.Collections;
//Код для создания
public class ShootScript : MonoBehaviour
{


    private PlayerControl playerControl;
    public Transform sword;
    

    public float shootingRate = 0.25f;

    public bool isEnemy = true;

    private float shootCooldown;
    private MoveScript move;

    public float fireRate = 0.5f;
    private float nextFire = 1f;
    void Start()
    {
        
        playerControl = GetComponent<PlayerControl>();
       
        move = GetComponent<MoveScript>();
    }

    void Update()
    {
        
        if (nextFire > 1)
        {
            nextFire -= Time.deltaTime;
        }
        
    }
    public void Attack(bool isEnemy)
    {
       
            if (CanAttack && Time.time>nextFire)
            {

            nextFire = Time.time + fireRate;
            var shootTransform = Instantiate(sword) as Transform;


                shootTransform.position = transform.position;


                MoveScript move = shootTransform.gameObject.GetComponent<MoveScript>();
                if (move != null)
                {



                    move.direction = this.transform.right;


                }
            }
        
    }


    public bool CanAttack
    {
        get
        {
            return shootCooldown <= 0f;
            
        }
    }
}

Код для самой пули
using UnityEngine;
using System.Collections;

public class MoveScript : MonoBehaviour
{
	public Vector2 speed = new Vector2(80, 80);
	public Vector2 direction = new Vector2(0, 0);
	
	private Vector2 movement;
	private Rigidbody2D rigidbodyComponent;
    private PlayerControl player;
	void Start()
    {
        player = GetComponent<PlayerControl>();
    }
	void Update()
	{
      

           movement = new Vector2(
           speed.x * direction.x * 1,
           speed.y * direction.y * 1);
    }
	void OnCollisionEnter2D(Collision2D  collision) {
		if (collision.transform.tag == "Ground" || collision.transform.tag == "Side") {
			speed = new Vector2(0,0);

		}

	}
   

    void FixedUpdate()
	{
		if (rigidbodyComponent == null) rigidbodyComponent = GetComponent<Rigidbody2D>();
		

		rigidbodyComponent.velocity = movement;
	}
}

Код для создания пули
using UnityEngine;
using System.Collections;

public class WeaponControlScript : MonoBehaviour {
    public KeyCode Fire = KeyCode.F;
    private ShootScript shootScript;
    private PlayerControl player;
    // Use this for initialization
    void Start () {
        player = GetComponent<PlayerControl>();
        shootScript = GetComponent<ShootScript>();
    }
	
	// Update is called once per frame
	void Update () {
        
        
            if (Input.GetKeyDown(Fire))
            {
                shootScript.Attack(true);

            }
        
	}
}

Если в в MoveScript поменять на
if (player.isFacingRight == true)
        {
            movement = new Vector2(
            speed.x * direction.x * 1,
            speed.y * direction.y * 1);
        } else if  (player.isFacingRight == false)
            {
                movement = new Vector2(
                speed.x * direction.x * -1,
                speed.y * direction.y * 1);
            }

Пуля просто падает. Мне нужно сделать так чтобы пуля в сторону где был курсор при нажатия кнопки Fire.3766ac252402467eba0f8bc8d2d490e7.png5ba6eca4c39f48b0bc6502a57cd68a1b.pngКак поменять направление пули? Она всегда летит вправо.
  • Вопрос задан
  • 1941 просмотр
Решения вопроса 2
BasmanovDaniil
@BasmanovDaniil
Геймдизайнер-телепат
Пуля летит вправо, потому что внутри ShootScript ей задаётся такое направление:
MoveScript move = shootTransform.gameObject.GetComponent<MoveScript>();
if (move != null)
{
    move.direction = this.transform.right;
}

Зададите другое - полетит в другую сторону. Нужный вектор можно найти с помощью Input.mousePosition и Camera.ScreenToWorldPoint.
А вообще говоря, специально для таких случаев юнити создаёт проекты-туториалы, где есть готовые скрипты, которые можно изучать и делать своё, либо использовать как есть.
Ответ написан
Jurajkeee
@Jurajkeee Автор вопроса
Baby Developer
if (Input.GetKeyDown(Fire))
{
Vector3 worldMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = (Vector2)((worldMousePos - transform.position));
direction.Normalize();
GameObject bullet = (GameObject)Instantiate(
rocket,
transform.position + (Vector3)(direction * 0.5f),
Quaternion.identity);
bullet.GetComponent().velocity = direction * speed;
bullet.AddComponent();
bullet.AddComponent();
}
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы