I am scripting the movement of the main camera on the XZ axis. The camera should move horizontally (forward, back, right, left) when the cursor approaches one of the corresponding screen edges. The right-left movement works perfectecly regarless of the orientation of the camera;
if (Input.mousePosition.y >= Screen.height - brdThcknss)
{ //this line is to be replaced
//transform.Translate(Vector3.forward * Time.deltaTime * panSpeed);
}
if (Input.mousePosition.y <= brdThcknss)
{//this line is to be replaced
//transform.Translate(Vector3.back * Time.deltaTime * panSpeed);
}
if (Input.mousePosition.x >= Screen.width - brdThcknss)
{
transform.Translate(Vector3.right * Time.deltaTime * panSpeed);
}
if (Input.mousePosition.x <= brdThcknss)
{
transform.Translate(Vector3.left * Time.deltaTime * panSpeed);
}
It is also necessary to mention that the camera should move througout the XZ plane of the world regardless of the angle of the camera (the camera orbits). What could I replace the commented lines for so that the camera performs the desired movement?
Thanks man. This would work perfectly if the camera didn’t orbit. Nonetheless, moving the camera with respect to the global z axis becomes counterintuitive when the camera has orbited 180 degrees. I would like the camera to move forward and back regardless of the orientation.
Nonetheless, the result is the same. I was wondering if it is possible to make a copy the normalized vector transform.forward, modify this copy so its z axis is pointing forward, and then use this modified copy in the method.
If we’re adding a vector without a y component and the y component is changing… that doesn’t make sense. Something else is changing the y component. Do you have another script attached somewhere?
I had this exact same problem about a week ago. What you are experiencing also causes other issues when you start zooming in and rotating the camera. Sometimes you get stuck in a tight zoom if you go forward and the camera is getting closer to the ground! Anyway, here is the answer:
Vector3 panMove = this.transform.up
panMove.y = 0f; // This is the main part you are looking for
transform.Translate(panMove * Time.deltaTime * panSpeed, Space.World); // You still have to do Space.World
UpdateCameraOffset(); // You'll need this later. Trust me.
I think the code speaks for itself but basically, you are translating (or adding) a Vector3 to the cameras current transform. The part you were missing is that you want to ignore the Y value so you set it to 0 before you apply the Vector. This script is assuming you have it placed on the camera.
You can remove the UpdateCameraOffset() for now but it my game, I wanted to center the camera on my player when it was their turn. I have about 3 functions to handle this and it required me to get the current offset of the ground (since it appears you have free camera movement like mine). Let me know if this is something you need as well.