Четверг, 28 Марта 2024, 23:28

Приветствую Вас Гость

[ Новые сообщения · Игроделы · Правила · Поиск ]
  • Страница 1 из 1
  • 1
Форум игроделов » Движки для разработки игр и сложные системы разработки » Unity » Прицел в FPS
Прицел в FPS
AnGeJI96Дата: Воскресенье, 10 Апреля 2016, 10:55 | Сообщение # 1
был не раз
Сейчас нет на сайте
Здравствуйте, подскажите пожалуйста как реализовать автоприцел в FPS, чтобы при нахождении прицела рядом с объектом он двигался на сам объект?

Код


using UnityEngine;
using System.Collections;

public class FPSMouseLook : MonoBehaviour
{

    public enum RotationAxes { MouseX, MouseY, MouseOrbit}
    public RotationAxes axes = RotationAxes.MouseX;
    public float dist;
    [HideInInspector]
    public Transform target; //This needed to be assigned in case of MouseOrbit option selected

    float currentSensitivityX = 1.5F;
    float currentSensitivityY = 1.5F;

    float sensitivityX = 1.5F;
    float sensitivityY = 1.5F;

    float minimumY = -60F;
    float maximumY = 60F;
    
    float rotationX = 0F;
    float rotationY = 0F;

    float minimumX = -360F;
    float maximumX = 360F;
    
    Quaternion originalRotation;

    bool doingRecoil = false;
    float recoilAmount = 0.15f;
    float tempRecoil = 0;

    float distance = 5.0f;
    bool reachedTarget = false;

    void Start ()
    {
  // Make the rigid body not change rotation
  if (GetComponent<Rigidbody>())
        {
   GetComponent<Rigidbody>().freezeRotation = true;
  }

  originalRotation = transform.localRotation;
    }
    
    void LateUpdate ()
    {
  if(GameSettings.menuOpened)
   return;

  if(currentSensitivityX != GameSettings.mouseSensitivity || currentSensitivityY != GameSettings.mouseSensitivity)
        {
   currentSensitivityX = currentSensitivityY = GameSettings.mouseSensitivity;
  }

  sensitivityX = currentSensitivityX * (GameSettings.currentFOV/GameSettings.defaultFOV);
  sensitivityY = currentSensitivityY * (GameSettings.currentFOV/GameSettings.defaultFOV);

  if (axes == RotationAxes.MouseX)
        {

#if UNITY_ANDROID || UNITY_IOS || UNITY_WP8 || UNITY_WP8_1
            rotationX += GameSettings.lookDirection.x * sensitivityX;
#else

   
   rotationX += Input.GetAxis("Mouse X") * sensitivityX;
            

#endif

            rotationX = ClampAngle(rotationX, minimumX, maximumX);
            Quaternion xQuaternion = Quaternion.AngleAxis (rotationX, Vector3.up);
   transform.localRotation = originalRotation * xQuaternion;
  }

  if (axes == RotationAxes.MouseY)
        {

#if UNITY_ANDROID || UNITY_IOS || UNITY_WP8 || UNITY_WP8_1
            rotationY += GameSettings.lookDirection.y * sensitivityY;
#else
   rotationY += Input.GetAxis("Mouse Y") * sensitivityY;

#endif

            rotationY = ClampAngle(rotationY, minimumY, maximumY);
            Quaternion yQuaternion = Quaternion.AngleAxis (-rotationY, Vector3.right);
   transform.localRotation = originalRotation * yQuaternion;
  }

  if (axes == RotationAxes.MouseOrbit && reachedTarget && target)
        {

#if UNITY_ANDROID || UNITY_IOS || UNITY_WP8 || UNITY_WP8_1
            rotationX += GameSettings.lookDirection.x * sensitivityX;
            rotationY += GameSettings.lookDirection.y * sensitivityY;
#else
            rotationX += Input.GetAxis("Mouse X") * sensitivityX;
            rotationY -= Input.GetAxis("Mouse Y") * sensitivityY;
#endif

            rotationX = ClampAngle (rotationX, minimumX, maximumX);
   rotationY = ClampAngle (rotationY, minimumY, maximumY);

   Quaternion rotation = Quaternion.Euler(rotationY, rotationX, 0);
   Vector3 position = rotation * new Vector3(0.0f, 0.0f, -distance) + target.position;
    
   transform.rotation = rotation;
   transform.position =  position;
  }
    }
    
    public static float ClampAngle (float angle, float min, float max)
    {
  if (angle < -360F)
        {
   angle += 360F;
  }

  if (angle > 360F)
        {
   angle -= 360F;
  }

  return Mathf.Clamp (angle, min, max);
    }

    public void Recoil()
    {
  //currentRecoil += recoilAmount;
  tempRecoil = 0;

  if(!doingRecoil)
        {
   StartCoroutine(SmoothRecoil());
  }
    }

    IEnumerator SmoothRecoil()
    {
  doingRecoil = true;

  while(tempRecoil < recoilAmount - 0.05f)
        {
   if(tempRecoil < recoilAmount/1.5f)
            {
    tempRecoil = Mathf.Lerp(tempRecoil, recoilAmount, Time.deltaTime * 15);
   }
            else
            {
    tempRecoil = Mathf.Lerp(tempRecoil, recoilAmount, Time.deltaTime * 9);
   }

   rotationY += tempRecoil;

   yield return null;
  }

  //tempRecoil = 0;
  //currentRecoil = 0;

  doingRecoil = false;
    }

    public void AssignTarget(Transform t1)
    {
  if(t1)
        {
   rotationX = t1.eulerAngles.y;
   rotationY = 25;
   target = t1;
   reachedTarget = false;
  }
        else
        {
   rotationX = transform.eulerAngles.y;
   rotationY = 0;
   target = null;
   reachedTarget = true;
  }

  if(target)
        {
   StopCoroutine("MoveToTarget");
   StartCoroutine("MoveToTarget");
  }
    }

    IEnumerator MoveToTarget ()
    {
  Quaternion rotation = Quaternion.Euler(rotationY, rotationX, 0);
  transform.rotation = rotation;
  while(target && Vector3.Distance(rotation * new Vector3(0.0f, 0.0f, -distance) + target.position, transform.position) > 0.1f)
        {
   transform.position = Vector3.MoveTowards(transform.position,  rotation * new Vector3(0.0f, 0.0f, -distance) + target.position, Time.deltaTime * 79);
   yield return null;
  }

  reachedTarget = true;
    }
}


Сообщение отредактировал AnGeJI96 - Воскресенье, 10 Апреля 2016, 10:55
BizzyДата: Воскресенье, 10 Апреля 2016, 11:08 | Сообщение # 2
постоянный участник
Сейчас нет на сайте
AnGeJI96, Юзай https://docs.unity3d.com/ScriptReference/Physics.BoxCast.html, дальше перебирай что больше понравится(то что ближе?) и поворачивай на этот объект который понравился.

AnGeJI96Дата: Воскресенье, 10 Апреля 2016, 11:31 | Сообщение # 3
был не раз
Сейчас нет на сайте
Bizzy, а не лучше будет так?
Код
public float fieldOfViewAngle = 110f;           // Number of degrees, centred on forward, for the enemy see.
    public GameObject aimTarget;
// If the angle between forward and where the player is, is less than half the angle of view...
  if(angle < fieldOfViewAngle * 0.5f)
  {
   RaycastHit hit;

   // ... and if a raycast towards the player hits something...
   if(Physics.Raycast(transform.position + transform.up, direction.normalized, out hit))
   {
    // ... and if the raycast hits the player...
    if(hit.collider.gameObject.tag == "ray")
    {
                    //...
    }


Сообщение отредактировал AnGeJI96 - Воскресенье, 10 Апреля 2016, 11:32
BizzyДата: Воскресенье, 10 Апреля 2016, 11:44 | Сообщение # 4
постоянный участник
Сейчас нет на сайте
AnGeJI96, Мне этот кусок кода вообще ничего не говорит....

AnGeJI96Дата: Воскресенье, 10 Апреля 2016, 12:59 | Сообщение # 5
был не раз
Сейчас нет на сайте
Bizzy,
Код
    void Update(){
   direction = aimTarget.transform.position - transform.position; // aimtarget цель
  float angle = Vector3.Angle(direction, transform.forward);

  // If the angle between forward and where the player is, is less than half the angle of view...
  if(angle < fieldOfViewAngle * 0.5f)
  {
   RaycastHit[] hit = Physics.SphereCastAll (transform.position, 5.0f, transform.forward, 1000f);

   // ... and if a raycast towards the player hits something...
   foreach(RaycastHit hits in hit)
   {

    // ... and if the raycast hits the player...
    if(hits.transform.tag == "ray")
    {
     Debug.Log ("///");
    }
   }    

  }
    }

И чтобы свести прицел, нужно от rotationX вычесть rot.x и от rotationY вычесть rot.y, где Vector rot = aimTarget.transform.position - transform.position?
BizzyДата: Воскресенье, 10 Апреля 2016, 13:09 | Сообщение # 6
постоянный участник
Сейчас нет на сайте
AnGeJI96, не проще LookAt ?

AnGeJI96Дата: Воскресенье, 10 Апреля 2016, 13:31 | Сообщение # 7
был не раз
Сейчас нет на сайте
Bizzy,Использовал LookAt и прицел не поворачивался, а двигался сам персонах вообще, тянуло к таргету

Добавлено (10 апреля 2016, 13:31)
---------------------------------------------
Bizzy, Из за того что я использую RotationAxes MouseX и MouseY, т.е на сам объект вешаю скрипт и выбираю на нем MouseX, а к объекту подвешена камера и на камере этот же скрипт, только с MouseY

BizzyДата: Воскресенье, 10 Апреля 2016, 14:09 | Сообщение # 8
постоянный участник
Сейчас нет на сайте
AnGeJI96, Ну и вчем собственно проблема? У тебя уже есть Таргет Объект, ну и поворачивай перса по оси Y а камеру по оси Х на таргет.
Код

transform.LookAt(target);
transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);

а для камеры тож самое только локальные координвты и ось Х.


AnGeJI96Дата: Воскресенье, 10 Апреля 2016, 16:05 | Сообщение # 9
был не раз
Сейчас нет на сайте
Bizzy, Спасибо большое, а через LookAt, скорость поворота можно изменить, чтобы скачками не было?
BizzyДата: Воскресенье, 10 Апреля 2016, 17:19 | Сообщение # 10
постоянный участник
Сейчас нет на сайте
AnGeJI96, через LookAt нет, чтобы плавно поворачивалось нужно делать так:
Код

var rotation = Quaternion.LookRotation(target.transform.position - transform.position);
transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, Time.deltaTime * rotationSpeed);
transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);




Сообщение отредактировал Bizzy - Воскресенье, 10 Апреля 2016, 17:20
AnGeJI96Дата: Воскресенье, 10 Апреля 2016, 19:58 | Сообщение # 11
был не раз
Сейчас нет на сайте
Bizzy, Спасибо большое, что помогли
Форум игроделов » Движки для разработки игр и сложные системы разработки » Unity » Прицел в FPS
  • Страница 1 из 1
  • 1
Поиск:

Все права сохранены. GcUp.ru © 2008-2024 Рейтинг