如何锁定相机? Unity2D

时间:2017-08-21 00:05:29

标签: c# android unity3d

当我到达我的地图边缘时,无论是右侧还是左侧,相机都会锁定,但仍允许我的玩家向前移动直到我转身。 我知道我需要使用mathf.clamp,但我不确定如何将它应用于我当前的代码。谢谢。

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

public class walkScript : MonoBehaviour {

    public float speed = 1.5f;
    private Vector3 target;
    private Vector3 lastTarget;
    private Animator animator;

    private Vector3 camTarget;
    public GameObject cameraMain;

    void Start () {
        target = transform.position;
        camTarget = cameraMain.transform.position;
        animator = GetComponent<Animator> ();
    }

    void Update () {
        if (Input.GetMouseButtonDown(0)) {
            target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            target.z = transform.position.z;
            target.y = transform.position.y;

            camTarget = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            camTarget.z = cameraMain.transform.position.z;
            camTarget.y = cameraMain.transform.position.y;
            flipCharacter ();
        }
        transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
        cameraMain.transform.position = Vector3.MoveTowards(cameraMain.transform.position, camTarget, speed * Time.deltaTime);
        lastTarget.x = target.x;
    }    
    private void flipCharacter()
    {
        if (lastTarget.x > target.x) {
            animator.transform.Rotate(0, 180, 0);
        } else if (lastTarget.x < target.x) {
            animator.transform.Rotate(0, 180, 0);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您好! 这段代码应该有用。

public Vector2 mapLimit;
void Update() {
    if (Input.GetMouseButtonDown(0)) {
        target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        target.z = transform.position.z;
        target.y = transform.position.y;

        camTarget = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        camTarget.z = cameraMain.transform.position.z;
        camTarget.y = cameraMain.transform.position.y;

        camTarget.x = Mathf.Clamp(camTarget.x, -mapLimit.x, mapLimit.x);
        camTarget.z = Mathf.Clamp(camTarget.z, -mapLimit.y, mapLimit.y);

        flipCharacter();
    }
    transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
    cameraMain.transform.position = Vector3.Lerp(cameraMain.trasform.position, camTarget, Time.deltaTime * speed); 
    lastTarget.x = target.x;
}