Есть ли способ сделать перекрестие, оставаясь неподвижным на оси Y игрока (2-й вид сверху) и перемещаясь по этой оси Y так же далеко, как курсор мыши? - PullRequest
0 голосов
/ 27 сентября 2019

Я настраиваю игру космических кораблей с другими друзьями с Unity, используя программирование на c #.Наша игра 2D с видением игрока сверху.Нам нужно сделать 2 перекрестия: одно, то есть замена курсора мыши (сделано), а ось космического корабля y следует за курсором мыши, чтобы космический корабль вращался вслед за перекрестием курсора мыши с задержкой.В это время задержки космический корабль не нацелен точно на перекрестие мыши, потому что вращение происходит не сразу, поэтому мы хотим сделать второе перекрестие, которое следует за осью Y космического корабля, чтобы игрок понял, когда вооружения корабля будут нацелены на позицию курсораименно так.Это второе перекрестие должно прокручиваться вдоль оси y корабля, чтобы расстояние между кораблем и курсором мыши было одинаковым между вторичным видоискателем по оси Y.Здесь вы можете найти пример игры: https://imgur.com/Uk7pW4x

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseCursor : MonoBehaviour{

public Texture2D cursorTexture;
public Transform aim;
public float aimSpeed = 3.0f;
private Vector2 cursorHotspot;
private Vector2 aim2;
private Vector3 mouseP;
private Vector2 direction;
// initialize mouse with a new texture with the
// hotspot set to the middle of the texture
// (don't forget to set the texture in the inspector
// in the editor)
void Start()
{
    cursorHotspot = new Vector2(cursorTexture.width / 2, cursorTexture.height / 2);
    Cursor.SetCursor(cursorTexture, cursorHotspot, CursorMode.Auto);
}

// To check where your mouse is really pointing
// track the mouse position in you update function
void Update()
{
    //from this the second crosshair code
    Vector3 currentMouse = Input.mousePosition;
    Ray ray = Camera.main.ScreenPointToRay(currentMouse);
    RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
    Debug.DrawLine(ray.origin, hit.point);

    var dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);

    aim2 = new Vector2(dir.x , dir.y);

    aim.transform.position = Vector2.MoveTowards(transform.position, aim2, aimSpeed);


}
}

На самом деле второе перекрестие остается в оси Y, как это исключено, но он не будет перемещаться так же далеко, как курсор мыши от корабля, так что обаперекрестие не полностью выровняет одно над другим.

1 Ответ

0 голосов
/ 27 сентября 2019

положить AIM в игрока, затем AIM взять ротацию игрока, и это основа кода AIM

'' 'C #

public Transform aim;//AIM position "aim image"
public float aimSpeed;//speed AIM
public float zonaMorta;//death zone value where the AIM can't move

private Vector3 target;//position where the AIM need to go
private Vector3 posAim;//AIM position

void Update ()
    {
        float pr = transform.rotation.z;//take the rotation value from the player
        float ty = Camera.main.ScreenToWorldPoint(Input.mousePosition).y;//y axis value of the mouse.
        target = new Vector3(0 , ty, 0);//allowance the y axis of the cursor to "target"
        posAim = aim.transform.position;//allowance AIM position to "posAim"
        posAim = new Vector3(0, posAim.y, 0);//on posAim I keep only y while x, z gate them

        if(posAim.y + zonaMorta > target.y && posAim.y - zonaMorta < target.y)//if AIM is between this two value then it can't move, it can't move in the y axis
    {

    }else{

        if(pr > -90f || pr < 90f){//if the rotation of the player is more than -90 degrees or less than 90 degrees then ..
            if(posAim.y > target.y)//if y axis of AIM is greater than the y axis of the cursor then..
            {
                aim.transform.position -= aim.transform.up * aimSpeed;//subtract and allowance at the AIM position a positive velocity in the y axis
            }
            if(posAim.y < target.y)//if y axis of AIM is lesser than the y axis of the cursor then..
            {
                    aim.transform.position += aim.transform.up * aimSpeed;//sum and allowance at the AIM position a positive velocity in the y axis
                }                   
                }
      if(pr < -90f || pr > 90f){//if the rotation of the player is less than -90 degrees or more than 90 degrees then ..

            if(posAim.y > target.y)//if y axis of AIM is greater than the y axis of the cursor then..
            {
                aim.transform.position -= -aim.transform.up * aimSpeed;//subtract and allowance at the AIM position a negative velocity in the y axis
            }
            if(posAim.y < target.y)//if y axis of AIM is lesser than the y axis of the cursor then..
            {
                    aim.transform.position += -aim.transform.up * aimSpeed;//sum and allowance at the AIM position a negative velocity in the y axis
                }                   
                }
            }
        }

' ''

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