如何在Unity3d中使摄像机平移js脚本

时间:2014-04-30 21:30:16

标签: android unity3d unityscript panning

我正在尝试制作以下相机平移js脚本,以便按原样工作,这意味着左右摇摄相机。到目前为止我所取得的成就是只将相机左右移动到起始位置。我不能让它在点击/触摸的gui.button上左右移动。

这是js脚本:

    #pragma strict

var target : GameObject;
var xpositionLeft = 10;
var xpositionRight = -10;
//var smooth : float = 5; // Don't know where should I put this var to make it pan smooth?

private static var isPanning = false;

function Update()
{
if(isPanning == true)
{
transform.position.x = target.transform.position.x;
transform.position.x = xpositionLeft;
    }
    else
    {
    transform.position.x = target.transform.position.x; // It only pan the camera left, not right!
    transform.position.x = xpositionRight;
    }
}

static function doPanning ()
    {
        isPanning = !isPanning;
    }

有人能说明如何使这个脚本有效吗?我是Unity和编程的新手,所以任何帮助都不仅仅是受欢迎的。 提前感谢大家的时间和答案。

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题。首先,行transform.position.x = target.transform.position.x;没有任何效果,因为您在下一行中立即覆盖它。您的代码基本上只在transform.position.x-10之间翻转10

其次,您期望的行为与代码中的逻辑不匹配。你只有两个状态,isPanning是真还是假,但你需要三种状态:pan leftpan rightdo nothing

// how far the camera should move witch each click
var xPositionOffset = 10;

// -1 = left, 0 = do dothing, 1 = right
var panDirection = 0;

function Update()
{
    if (panDirection != 0) // pan left/right
    {
        transform.position.x = transform.position.x + (panDirection * xPositionOffset);
        panDirection = 0;
    }
}

现在,您只需要将变量panDirection设置为-11,如果按下一个按钮,相机将移动到更远的位置。

如果您在使用矢量运算时出现问题,请查看Unity手册中的'Understanding Vector Arithmetic'章节。

上面的代码会使相机移动得不是很顺利,但这种方式更容易理解基本概念。您可以使用函数Vector3.MoveTowards来获得更平滑的移动,链接引用中显示的示例应该可以帮助您实现它。