Noticias

¡RECUERDA QUE SI ERES UN NUEVO USUARIO, DEBES PRESENTARTE PARA PODER PUBLICAR MENSAJES! | TENEMOS CANAL OFICIAL DE TELEGRAM: t.me/unity3dspain

Camara dinamica unity2d

Iniciado por Ness, Enero 02, 2016, 01:24:10 AM

Tema anterior - Siguiente tema
Enero 02, 2016, 01:24:10 AM Ultima modificación: Enero 02, 2016, 01:34:25 AM por nestorjaviersolera
Estoy desarrollando un juego y llevo tiempo queriendo hacer una cámara como la de los juegos Hotline Miami o Nuclear Throne, que tienen una cámara dinámica que sigue al jugador dejándolo en la zona central de la pantalla. Este es un tutorial que explica cómo hacerlo:
eature=oembed" frameborder="0" allowfullscreen="true">Tengo un código que puede servir, pero la cámara presenta problemas de posición y si muevo al jugador, la cámara se corre más de la cuenta.Aquí está el código: 
   using UnityEngine;
    using System.Collections;
   
    public class shauldspading : MonoBehaviour
    {
        public Transform Player;
        public Transform Mouse;
   
        // Use this for initialization
        void Start ()
        {
       
        }
       
        // Update is called once per frame
        void FixedUpdate ()
        {
            //var mousePos = Input.mousePosition;
            //Vector3 Mouse = Camera.main.ScreenToWorldPoint(mousePos);
   
            float xTo, yTo;
            Vector3 pos = transform.position;
            xTo = Player.position.x + lengthdir_x(Mathf.Min(9,Vector3.Distance(Player.transform.position, Mouse.transform.position)), Mouse.position);
            yTo = Player.position.y + lengthdir_y(Mathf.Min (9, Vector3.Distance (Player.transform.position, Mouse.transform.position)), Mouse.position);
            pos.x += (xTo - pos.x) / 25;
            pos.y += (yTo - pos.y) / 25;
            transform.position = pos;
        }
       
        float lengthdir_x(float len, Vector3 dir)
        {
            dir = dir.normalized * len;
            return dir.x;
        }
       
        float lengthdir_y(float len, Vector3 dir)
        {
            dir = dir.normalized * len;
            return dir.y;
        }
    }
Ya probé el código y me funciona, pero tiene el inconveniente de que no es fijo y si me muevo presenta problemas de posición. ¿Qué debería hacer para solucionar ese problema y mejorar el código que está arriba?
Video camara dinamica Nuclear Throne ejemplo de camara dinamica 2D:
">
 
tutorial del que esta basado el codigo anterior:
          Actualización codigo cortesia de http://es.stackoverflow.com/users/2186/moscoquera">moscoquera;  
using UnityEngine;
using System.Collections;


public class Camara_seguirObjeto : MonoBehaviour {

public GameObject objetivo;
public float Velocidad = 2f;
float ZOriginal=0;
Camera camara;
float internalVel=0;
float smoothRate=0.5f;
Vector3 velocidadCamara;
// Use this for initialization
void Start () {
   ZOriginal = transform.position.z;
   velocidadCamara = new Vector3(Velocidad,Velocidad,0);
}

// Update is called once per frame
void Update () {
   if (objetivo == null) {
      return;      
   }
   Vector3 tmp = Vector3.SmoothDamp(transform.position,
                                    objetivo.transform.position,
                                    ref velocidadCamara,
                                    this.smoothRate);
   tmp.z=ZOriginal;
   this.transform.position=tmp;
   
}
}
Este script debe ser añadido a la cámara en cuestión, y en "objetivo" se debe referencia al jugador en el mapa. 

Te ha faltado simular el desplazamiento lateral arriba/abajo de la camara al mover el cursor del ratón:Yo he utilizado un Empty GameObject emparentado al player como target(objetivo):
using UnityEngine;
using System.Collections;

//El script se añade a la camara
[RequireComponent(typeof(Camera))]
public class script3 : MonoBehaviour {

public Transform target; //Gameobject que hace de pivot
public float smoothTime = 0.5f; //tiempo smooth
public Vector2 desplazamiento = new Vector2(3f, 2f); //desplazamiento de origen
public Vector2 resolucion = new Vector2(800f,600f); //resolucion de origen


Vector3 velocity = Vector3.zero; //velocidad smooth
Vector3 centerScreen; //centro pantalla
Vector3 aspect; //aspecto ratio


void Start() {


   if(this.target == null){

      Destroy(this);
      Debug.Log("Asignar Target en script3 - " + this.name);
      Debug.Break();
      return;

   }

   this.centerScreen = new Vector3(Screen.width * 0.5f, Screen.height * 0.5f, 0f);
   //Recalcular desplazamiento en relacion a pantalla actual
   this.desplazamiento = new Vector2(this.desplazamiento.x * Screen.width / this.resolucion.x,
                                     this.desplazamiento.y * Screen.height / this.resolucion.y);
   this.aspect = new Vector3(this.desplazamiento.x / Screen.width, this.desplazamiento.y / Screen.height, 0f);

}

void Update () {

   Vector3 temp = this.target.position + Vector3.Scale(Input.mousePosition - this.centerScreen, this.aspect);
   this.transform.position = Vector3.SmoothDamp(this.transform.position, temp, ref this.velocity, this.smoothTime);

}

}
Tambien he considerado la resolucion de pantalla para efectuar los desplazamiento laterales del cursor del ratón.

Este era el scritp que necesitaba eres un capo Gracias.

Etiquetas: