Domanda

I am trying to make the following camera panning js script, to work as it should, meaning panning the camera left and right. What I have accomplished till now, is to move camera only left and back to its starting position. I can't get it move left and right on a gui.button being clicked/touched.

Here is the js script:

    #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;
    }

Can someone give a clue on how to make this script work? I'm new to Unity and programming, so any help is more than welcomed. Thank you all in advance for your time, and your answers.

È stato utile?

Soluzione

There are several problems with your code. First, the lines transform.position.x = target.transform.position.x; don't have any effect, because you're immediately overwriting it in the next line. Your code basically only flips transform.position.x between -10 and 10.

Second, the behavior you expect doesn't match the logic in your code. You have only two states, isPanning true and false, but you need three states: pan left, pan right and do 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;
    }
}

Now you only need to set the variable panDirection to -1 or 1 if one your buttons is pressed and the camera will move farther to that side.

If you're having trouble with the vector arithmetic, have a look at the chapter 'Understanding Vector Arithmetic' from the Unity manual.

The above code will move the camera not very smooth, but it's easier to understand the basic concept this way. You can use the function Vector3.MoveTowards to get a smoother movement and the example showed in the linked reference should help you to implement it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top