- Home /
Move camera when mouse is near the edges of the screen
void MoveCam()
{
Vector3 camPos = transform.position;
if (Input.mousePosition.x > screenWidth - 30)
{
isCamMoving = true;
camPos.x += speed * Time.deltaTime;
}
else if (Input.mousePosition.x < 30)
{
isCamMoving = true;
camPos.x -= speed*Time.deltaTime;
}
else if (Input.mousePosition.y > screenHeight - 30)
{
isCamMoving = true;
camPos.z += speed*Time.deltaTime;
}
else if (Input.mousePosition.y < 30)
{
isCamMoving = true;
camPos.z -= speed * Time.deltaTime;
}
else
{
isCamMoving = false;
}
}
why isn't this code working? I'm a noob btw. I have this in the update, I tried commenting out every other part of my camera scripts except this part and it still wasn't working. What's wrong with it?
What do you try to do exactly ? If I read your code, it seem that when you are on the edge of your screen you move horizontally/vertically and when you are inside the edges, you also move ? And what do not work as expected ?
Something that I directly see is that your y position is never checked since your 2 first if check the x position and one of them is always true... It is the same for your last else, which is evaluated only if you Input.mousePosotion is exactly 30,30. I think you should reorganize these things according to what you try to do.
Answer by Hellium · Apr 27, 2017 at 07:27 AM
You never assign the new position to your transform :
transform.position = camPos ;
camPos is assigned to transform.position on line 3, it should make the trick.
No, because Vector3 are structs, not instances of classes
Changing camPos
does not change transform.position
(Vector3 are value types, not reference types). Thus, at the end of the function, after you change the values of your camPos
vector, you must assign this new vector to the real transform.position
of your camera.
void $$anonymous$$oveCam()
{
Vector3 camPos = transform.position;
// $$anonymous$$ake change to camPos;
transform.position = camPos ;
}
Your answer
Follow this Question
Related Questions
How to make camera move like it does in the scene viewport? 0 Answers
Need help updating camera position to go above the player 2 Answers
Trouble converting transform.position to C# 1 Answer
How can i make my crosshair drag behind the camera? 0 Answers
How do I update values and the transform of an object on the server's and client's side? 0 Answers