Unity Player стреляет в себя - PullRequest
2 голосов
/ 18 октября 2019

У меня в игре есть следующая проблема:

На сцене два персонажа, и они могут стрелять друг в друга. Пустой игровой объект, прикрепленный перед друг другом, называется SpawnBullet, который порождает снаряд, как вы можете видеть на изображении.

enter image description here

Проблема в том, что игровой объект под названием «Игрок 2» стреляет в себя, пуля движется в его направлении. Даже когда я вращаю SpawnBullet. В Player 1 он работает нормально.

Этот скрипт прикреплен к игрокам

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Moviment : MonoBehaviour
{
    //player variables
    public GameObject player;
    public GameObject[] Personagens;

    //moving variables
    Vector3 targetPosition;
    float posY = 1;
    public float velocity = 0.2f;
    public float movMax = 3;
    public bool ismoving = false;
    public bool moveEnabled;
    public int aux;

    //bullet variables
    public GameObject projetil;
    private GameObject SpawBala;
    public float ProjetilVeloc = 500f;

    private void Start()
    {
        //sets the first unit as the active unit at the start of the game
        Personagens[0].GetComponent<Jogador>().isPlayer = true;
        TurnStart();

    }

    // Update is called once per frame
    void Update()
    {
        //left mouse button to start movement
        if (Input.GetMouseButtonDown(0))
        {
            //raycast checks and returns an object, if it's a tile, the unit moves
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            ismoving = true;

            if (Physics.Raycast(ray, out hit))
            {
                if (hit.transform.tag == "Tile")
                {
                    //checks if the tile is available based on the max movement of the unit
                    Tile tileAux = hit.transform.gameObject.GetComponent<Tile>();
                    Jogador scriptJog = player.GetComponent<Jogador>();
                    if ((tileAux.TilePostion.x - scriptJog.GridPosition.x) + (tileAux.TilePostion.y - scriptJog.GridPosition.y) >= -movMax && (tileAux.TilePostion.x - scriptJog.GridPosition.x) + (tileAux.TilePostion.y - scriptJog.GridPosition.y) <= movMax)
                    {
                        if ((tileAux.TilePostion.x - scriptJog.GridPosition.x) - (tileAux.TilePostion.y - scriptJog.GridPosition.y) >= -movMax && (tileAux.TilePostion.x - scriptJog.GridPosition.x) - (tileAux.TilePostion.y - scriptJog.GridPosition.y) <= movMax)
                        {
                            targetPosition = (hit.transform.position);
                            targetPosition.y = posY;
                            moveEnabled = true;
                        }

                    }
                }
            }

        }

        //right click to shoot
        if (Input.GetMouseButtonDown(1))
        {
            //raycast checks and returns an object, if it's a tile, the unit shoots
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit))
            {
                //checks if the tile is available based on the line and column of the unit
                Tile tileAux = hit.transform.gameObject.GetComponent<Tile>();
                Jogador scriptJog = player.GetComponent<Jogador>();

                if (tileAux.TilePostion.x == scriptJog.GridPosition.x || tileAux.TilePostion.y == scriptJog.GridPosition.y)
                {
                    if (tileAux.TilePostion.x > scriptJog.GridPosition.x)
                        tileAux.TilePostion.x = 5;
                    else
                        tileAux.TilePostion.x = 0;

                    if (tileAux.TilePostion.y > scriptJog.GridPosition.y)
                        tileAux.TilePostion.y = 5;
                    else
                        tileAux.TilePostion.y = 0;

                    Debug.Log(tileAux.TilePostion.x);
                    Debug.Log(tileAux.TilePostion.y);

                    //instantiates the bullet
                    GameObject tiro = Instantiate(projetil, SpawBala.transform.position, Quaternion.identity, player.transform);
                    Rigidbody BalaRigid = tiro.GetComponent<Rigidbody>();
                    BalaRigid.AddForce(Vector3.forward * ProjetilVeloc);
                }
            }
        }

        //player moves until reaches the position
        if (player.transform.position != targetPosition)
        {
            player.transform.position = Vector3.MoveTowards(player.transform.position, targetPosition, velocity);
            if (player.transform.position == targetPosition)
                ismoving = false;
        }

        //if player reaches position, it's deselected
        if (moveEnabled && !ismoving)
        {
            player.GetComponent<Jogador>().isPlayer = false;
            moveEnabled = false;
        }
    }

    public void TurnStart()
    {
        //makes the selected unit the active unit
        for (int i = 0; i < Personagens.Length; i++)
        {
            if (Personagens[i].GetComponent<Jogador>().isPlayer == true)
            {
                player = Personagens[i];
                posY = player.transform.position.y;
                targetPosition = player.transform.position;
                SpawBala = player.transform.GetChild(0).gameObject;
            }
        }
    }

    public void TurnEnd()
    {
        //desactivates all units
        for(int i = 0; i < Personagens.Length; i++)
        {
            Personagens[i].GetComponent<Jogador>().isPlayer = false;
        }
    }
}

И я использую этот раздел (скопированный сверху) для стрельбы:

//right click to shoot
        if (Input.GetMouseButtonDown(1))
        {
            //raycast checks and returns an object, if it's a tile, the unit shoots
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit))
            {
                //checks if the tile is available based on the line and column of the unit
                Tile tileAux = hit.transform.gameObject.GetComponent<Tile>();
                Jogador scriptJog = player.GetComponent<Jogador>();

                if (tileAux.TilePostion.x == scriptJog.GridPosition.x || tileAux.TilePostion.y == scriptJog.GridPosition.y)
                {
                    if (tileAux.TilePostion.x > scriptJog.GridPosition.x)
                        tileAux.TilePostion.x = 5;
                    else
                        tileAux.TilePostion.x = 0;

                    if (tileAux.TilePostion.y > scriptJog.GridPosition.y)
                        tileAux.TilePostion.y = 5;
                    else
                        tileAux.TilePostion.y = 0;

                    Debug.Log(tileAux.TilePostion.x);
                    Debug.Log(tileAux.TilePostion.y);

                    //instantiates the bullet
                    GameObject tiro = Instantiate(projetil, SpawBala.transform.position, Quaternion.identity, player.transform);
                    Rigidbody BalaRigid = tiro.GetComponent<Rigidbody>();
                    BalaRigid.AddForce(Vector3.forward * ProjetilVeloc);
                }
            }
        }

1 Ответ

1 голос
/ 18 октября 2019

Когда вы добавляете силу к пуле, которую вы используете Vector3.forward. Вместо этого вам нужно использовать transform.forward.

Vector3.forward всегда является константой (0, 0, 1). Думайте об этом как о направлении вашего мира. Он никогда не изменится.

transform.forward однако даст направление движения GameObject (игрока) вперед. Когда вы поворачиваете своего игрока, его трансформация.forward изменится соответственно.

Причина, по которой игрок 1 работает правильно, заключается в том, что он направлен в том же направлении, что и Vector3.forward.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...