I’m having a very strange issue. I’ve written a script to handle my player camera’s movement, which I wanted to have the following functions:
- Follow the player on a delay (player movement is already smooth so 1:1 movement is perfect), and
- When the mouse moves to the edges of the screen, “look” in that direction, smoothly gliding some fixed distance away from the player.
The first function was trivial to implement, I simply used a List that stored changes in player position and had camera read from it.
void FollowPlayer()
{
positionTable.Insert(followDelay - 1, followedObject.transform.position);
this.transform.Translate(positionTable[0] - this.transform.position + zOffset);
positionTable.RemoveAt(0); //remove first index, queuing next movement
}
The second function took a little more work, but I was able to get it working… independently.
void FollowMouse()
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); //mouse pos in world coords
Vector3 relativePos = mousePos - this.transform.position; //directions from us to mouse cursor
if (relativePos.magnitude < mouseDeadzone)
{
targetMouseDelta = Vector2.zero;
}
else
{
targetMouseDelta = mouseLookDistance * new Vector2(relativePos.x, relativePos.y).normalized;
}
Vector2 moveVector = (targetMouseDelta - currentMouseDelta) * mouseLookSpeed;
currentMouseDelta += moveVector;
this.transform.Translate(moveVector.x, moveVector.y, 0);
}
Basically, this code uses a delta to keep track of where the camera is relative to where it would be without any mouse input. This way it should play nice when other things are actively affecting movement.
Now, the strange part. FollowMouse() works as expected, but only when FollowPlayer() is not being run.
Why is this? The behavior when FollowPlayer() is being run is very strange. The first frame, the position updates correctly but for every frame afterwards it moves the camera in the opposite direction I give as input.
Thinking this might be a gotcha when calling Translate() twice in a row, I tried storing both inputs and adding them together for inputs to a single Translate() call but that had the same effect.