【问题标题】:Move Camera in UnityScript 2d in C#在 C# 中的 UnityScript 2d 中移动相机
【发布时间】:2016-04-09 19:39:59
【问题描述】:

我刚开始编写 Unity 2d,遇到了一个大问题:如何移动相机?该脚本附加到对象“播放器”。我希望它与播放器一起移动。谢谢!

/*
I 
*/
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
 public float speed = 10; //Float for speed
 public string hAxis = "Horizontal";
 void Start ()
 {
     //empty
 }

 void FixedUpdate ()
 {
         if (Input.GetAxis (hAxis) < 0) //Left
         {

                 Vector3 newScale = transform.localScale;
                 newScale.y = 1.0f;
                 newScale.x = 1.0f;
                 transform.localScale = newScale;
         } 
         else if (Input.GetAxis (hAxis) > 0) //Right
         {
                 Vector3 newScale =transform.localScale;
                 newScale.x = 1.0f;
                 transform.localScale = newScale;        
         }
        //Position transformation
    transform.position = transform.position + transform.right * Input.GetAxis(axisName) * speed * Time.deltaTime;
 }
}

【问题讨论】:

    标签: c# 2d unityscript


    【解决方案1】:

    无需任何脚本,您只需将相机游戏对象拖动为玩家的子对象,相机就会开始跟随玩家位置。

    对于脚本,试试这个,将播放器设置为目标。

    using UnityEngine;
     using System.Collections;
    
     public class SmoothCamera2D : MonoBehaviour {
    
         public float dampTime = 0.15f;
         private Vector3 velocity = Vector3.zero;
         public Transform target;
    
         // Update is called once per frame
         void Update () 
         {
             if (target)
             {
                 Vector3 point = camera.WorldToViewportPoint(target.position);
                 Vector3 delta = target.position - camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z)); //(new Vector3(0.5, 0.5, point.z));
                 Vector3 destination = transform.position + delta;
                 transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
             }
    
         }
     }
    

    【讨论】:

    • 但是我是否将主摄像头附加到对象上,屏幕是蓝色的!
    • 检查作为播放器子代的摄像机的变换,确保 x 和 y 的值为 0(与播放器相同的位置)并且 z 为负值(在播放器后面)。
    • 查看 Camera 组件,检查 Size 属性,更改该值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    相关资源
    最近更新 更多