Pan, Zoom and limit camera movement - Unity 2D Tutorial

  Рет қаралды 64,982

Shack Man

Shack Man

Күн бұрын

Пікірлер: 117
@МК264
@МК264 4 ай бұрын
Great tutorial Managed to hold my picture in the center on maximal zoomout by changing two lines: float minX = mapMinX + Mathf.Min(camWidth, mapRender.bounds.size.x / 2f); float maxX = mapMaxX - Mathf.Min(camWidth, mapRender.bounds.size.x / 2f);
@piotrek228
@piotrek228 2 жыл бұрын
Thanks for the video, everything works. I am pasting the code for others: using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraMovement : MonoBehaviour { [SerializeField] private Camera cam; //obiekt kamery [SerializeField] private float zoomStep, minCamSize, maxCamSize; //zakres powiększenia [SerializeField] private SpriteRenderer mapRenderer; private float mapMinX, mapMaxX, mapMinY, mapMaxY; private Vector3 dragOrigin; private void Awake() { mapMinX = mapRenderer.transform.position.x - mapRenderer.bounds.size.x / 2f; mapMaxX = mapRenderer.transform.position.x + mapRenderer.bounds.size.x / 2f; mapMinY = mapRenderer.transform.position.y - mapRenderer.bounds.size.y / 2f; mapMaxY = mapRenderer.transform.position.y + mapRenderer.bounds.size.y / 2f; } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { PanCamera(); } //przesuwanie pozycji kamery (lewo, prawo, góra, dół) private void PanCamera() { if (Input.GetMouseButtonDown(0)) dragOrigin = cam.ScreenToWorldPoint(Input.mousePosition); if (Input.GetMouseButton(0)) { Vector3 difference = dragOrigin - cam.ScreenToWorldPoint(Input.mousePosition); print("origin " + dragOrigin + " newPosition " + cam.ScreenToWorldPoint(Input.mousePosition) + " =difference" + difference); //cam.transform.position += difference; //bez ograniczenia obszaru cam.transform.position = ClampCamera(cam.transform.position + difference); //ograniczenie obszaru } /* if (Input.GetMouseButtonDown(0)) dragOrigin = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, cam.transform.position.z * -1)); if (Input.GetMouseButton(0)) { Vector3 difference = dragOrigin - cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, cam.transform.position.z * -1)); Debug.Log("origin " + dragOrigin + " newPosition " + cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, cam.transform.position.z * -1)) + " =difference " + difference); cam.transform.position += new Vector3(difference.x, difference.y, 0f); } */ } public void ZoomIn() { float newSize = cam.orthographicSize - zoomStep; cam.orthographicSize = Mathf.Clamp(newSize, minCamSize, maxCamSize); cam.transform.position = ClampCamera(cam.transform.position); //ograniczenie obszaru } public void ZoomOut() { float newSize = cam.orthographicSize + zoomStep; cam.orthographicSize = Mathf.Clamp(newSize, minCamSize, maxCamSize); cam.transform.position = ClampCamera(cam.transform.position); //ograniczenie obszaru } private Vector3 ClampCamera(Vector3 targetPosition) { float camHeight = cam.orthographicSize; float camWidth = cam.orthographicSize * cam.aspect; float minX = mapMinX + camWidth; float maxX = mapMaxX - camWidth; float minY = mapMinY + camHeight; float maxY = mapMaxY - camHeight; float newX = Mathf.Clamp(targetPosition.x, minX, maxX); float newY = Mathf.Clamp(targetPosition.y, minY, maxY); return new Vector3(newX, newY, targetPosition.z); } }
@klajswister
@klajswister 2 жыл бұрын
polska gurom
@ЕваАвокадо-з3ф
@ЕваАвокадо-з3ф 2 ай бұрын
This is the best video on this topic! I've tried a lot of ways to move around the sprite in this way, and all of them were not very good. But your way was the best! It's also very simple. Thanks!
@jacobgsm
@jacobgsm 3 жыл бұрын
Great video. Thanks for all of the details and explanations, as opposed to just instructions on what to do. You made it easy to understand why things are happening, not just what is happening.
@ShackMan
@ShackMan 3 жыл бұрын
Thanks!
@victorkuzmin3416
@victorkuzmin3416 11 ай бұрын
Man, you saved me hours. One of the best and clear explanation.
@friesneverdies
@friesneverdies 2 жыл бұрын
anyone who needs a scroll wheel to zoom in and out add this in the update function if (Input.GetAxis("Mouse ScrollWheel") > 0f) // forward { ZoomIn(); } else if (Input.GetAxis("Mouse ScrollWheel") < 0f) // backwards { ZoomOut(); }
@nuhu784
@nuhu784 Жыл бұрын
Thanks
@bartmanp.4734
@bartmanp.4734 3 жыл бұрын
who would have guessed that I would stumble upon the exact tutorial I need! Thanks!!
@ShackMan
@ShackMan 3 жыл бұрын
Probably the youtube algorithm that already knows what you're gonna need next week ;-)
@urselhorst9253
@urselhorst9253 Жыл бұрын
thats exactly what i needed man that was awesome. I used DOTween for the zoom animation which makes it feel a lot smoother
@aminacrawford9761
@aminacrawford9761 Жыл бұрын
thnx so much man been struggling for about like 4 hours now tysm!!!
@andrewgray9797
@andrewgray9797 2 жыл бұрын
For anyone who wants to zoom in/out with the mouse wheel and clamp the size of the camera to the width of the map, I think this is right? Maybe Shack Man can let me know. It works for me: void Update() { if (Input.GetAxis("Mouse ScrollWheel") > 0f) { ZoomIn(); } if (Input.GetAxis("Mouse ScrollWheel") < 0f) { ZoomOut(); } } private void ZoomIn() { float newSize = cam.orthographicSize - zoomStep; cam.orthographicSize = Mathf.Clamp(newSize, minCamSize, Mathf.Min(maxCamSize, (mapRenderer.bounds.size.x / 2f) / cam.aspect)); cam.transform.position = ClampCamera(cam.transform.position); } private void ZoomOut() { float newSize = cam.orthographicSize + zoomStep; cam.orthographicSize = Mathf.Clamp(newSize, minCamSize, Mathf.Min(maxCamSize, (mapRenderer.bounds.size.x / 2f) / cam.aspect)); cam.transform.position = ClampCamera(cam.transform.position); }
@ShadowTitan100
@ShadowTitan100 Жыл бұрын
Thank you!
@FuryTheFurious
@FuryTheFurious 10 ай бұрын
tysm
@0_0hyunni
@0_0hyunni 5 ай бұрын
WoW~! Thank you so much! This helped me a lot to start a new project!
@munchkis
@munchkis 4 ай бұрын
best tutorial on this, thank you
@Fresch1990
@Fresch1990 3 жыл бұрын
Just came by to leave a like. Thank you Sir! Everything i needed in a straight to the point video.
@technoo4891
@technoo4891 4 жыл бұрын
Amazing and useful tutorial brother, thank you for the great content.
@DanutJMK
@DanutJMK 11 ай бұрын
Different engines, same logic. Thanks!
@WishMakerDX
@WishMakerDX 3 жыл бұрын
Awesome tutorial, needed something to make sure the camera's corners didn't go outside the boundaries regardless of zoom size and this did the trick! :D
@MxxMkk
@MxxMkk Ай бұрын
You are the best, thx. Still actual and helpful
@sergejlopatkin3149
@sergejlopatkin3149 3 жыл бұрын
Thank you man, was searching for ever to find something like this video. Helped a lot!
@YayapipiStudio
@YayapipiStudio 2 жыл бұрын
Another idea for the zoom-out clamp: - Add the code below at the end of zoom out function: _cam.transform.position = ClampCamera(_camera.transform.position);
@Rexcode
@Rexcode 3 жыл бұрын
These tutorials are useful and simple, Thanks for this!
@lostdragon_1
@lostdragon_1 4 жыл бұрын
These are good tutorials. I like the tilemap ones too.
@indiandev1588
@indiandev1588 3 жыл бұрын
sir u have any idea of canvas move with mouse sir pls reply
@jayanth2209
@jayanth2209 3 жыл бұрын
Great tutorial. Helped me save a lot of time. Thanks a lot!!
@renata_navarro
@renata_navarro Жыл бұрын
It Works like a charm, but I don´t have an image to do it, so I used 2 Vector2 to adjust the borders. TY
@AleySoundz
@AleySoundz Жыл бұрын
Can you please explain the last part. How to not zoom beyond the map?!
@dudelios3123
@dudelios3123 2 жыл бұрын
Thanks a lot for this. It's a big help. Keep up the good work.
@ShackMan
@ShackMan 2 жыл бұрын
Thanks!
@irgendein2.account432
@irgendein2.account432 3 жыл бұрын
That was exactly what i searched for, thank you very much
@valeriag.3324
@valeriag.3324 2 жыл бұрын
Thank you very much for the tutorial !!! Helped me a lot
@lordheman
@lordheman 2 жыл бұрын
THANK YOU! My breakthrough (learned from you) came when using a sprite, to set the borders of the camera movement!
@shiyaromischannel9542
@shiyaromischannel9542 3 жыл бұрын
A huge thanks for this awesome help!
@mrussoart
@mrussoart Жыл бұрын
Thanks a lot!
@shung0209
@shung0209 2 жыл бұрын
Awesome video, it really helped me a lot!
@Ghost-2079
@Ghost-2079 2 жыл бұрын
really useful tutorial, thanks a lot friend
@1nexts
@1nexts 2 жыл бұрын
Thank you very much. Great tutorial + save a lot of time.
@mihailmalikov7538
@mihailmalikov7538 3 жыл бұрын
Great tutorial! Thanks!
@WanP1su
@WanP1su 2 жыл бұрын
Thanks a lot! This is better way to create bounds then use Cinemachine
@palanolho82
@palanolho82 9 ай бұрын
Hi, How would you adjust the clamp if using a perspective camera instead of orthogonal ? many thanks in advance.
@vanshtandon1829
@vanshtandon1829 5 ай бұрын
Awesome 👍
@thePRODYLAN
@thePRODYLAN 2 жыл бұрын
How would you make the pan go farther than the mouse, like when dragging it will move past the mouse position?
@dmytrokorsunskyi
@dmytrokorsunskyi 3 жыл бұрын
Thank you, helped me alot!
@podrix
@podrix 2 жыл бұрын
Hi, love the video. Just a question, how would you go about clamping the position of the camera if you are using a UI RawImage instead of a SpriteRenderer?
@cake8242
@cake8242 3 ай бұрын
Can you make a tutorial for this with the new imput system?
@kyokaishiro7944
@kyokaishiro7944 2 жыл бұрын
Camera coded in 10 minutes thanks you
@anima9266
@anima9266 11 ай бұрын
Thank you for this video but i got a problem ut sometimes turn blue or the sprite turn invisible sometimes im still looking for solutions 😢
@GamingTherapy8890
@GamingTherapy8890 7 ай бұрын
can you please explain how origin point and newPosition become same after some time. despite position on screen is different than origin position
@lennardfischomode1940
@lennardfischomode1940 2 жыл бұрын
I tried to use the first part of the code with just the camera movement but it didnt work for me. I got the console output but my camera didnt move. anyone got an idea?
@GenJeFT
@GenJeFT 2 жыл бұрын
Same problem.
@chrissmalls4462
@chrissmalls4462 Жыл бұрын
Make sure your camera is on orthographic projection
@tommedenney
@tommedenney Жыл бұрын
im having the same issue. my camera is set up correctly in orth view and code is correct as well
@well5832
@well5832 4 жыл бұрын
all works perfectly
@guest7play614
@guest7play614 2 жыл бұрын
man you are amazing
@stiluboy
@stiluboy 11 ай бұрын
Why I cannot see "ScreenToWorldPoint" in my Unity ? do I need to add it somehow ?
@bioman1hazard607
@bioman1hazard607 4 жыл бұрын
can you link the script file, its very cumbersome to rewrite the whole thing if i make a mistake. also my camera keeps jittering when i move it in game, whats going on?
@Jarzykk
@Jarzykk 3 жыл бұрын
Have you solved this problam? I have the same.
@bioman1hazard607
@bioman1hazard607 3 жыл бұрын
@@Jarzykk sadly not yet, I think I have an idea, tho it's not concrete as i dont have a copy of the code directly to compare properly
@bioman1hazard607
@bioman1hazard607 3 жыл бұрын
It may have something to do with swapping x and z, plus this is completely useless if you use the new input
@Jarzykk
@Jarzykk 3 жыл бұрын
@@bioman1hazard607 Thank you for the answer, Artemis!
@spikeweb5193
@spikeweb5193 Жыл бұрын
I want build big soace level. How canni do borders when ship cant move?
@anellaa5070
@anellaa5070 Жыл бұрын
hi, im only need pan and boundary but somehow I can't get the boundary working any idea why?
@anellaa5070
@anellaa5070 Жыл бұрын
also i only want to pan on the x axis and the y axis just staying still
@andreyrosiaev8613
@andreyrosiaev8613 2 жыл бұрын
Hi thanks for the video, do you have any ideas how I could add an offset camera to the limit for the UI panel?
@davidmartin3772
@davidmartin3772 2 жыл бұрын
just for anyone who wants zoom when you scroll with the mouse: void zoom() { if (Input.GetAxis("Mouse ScrollWheel") > 0f) { float newSize = mainCamera.orthographicSize - zoomStep; mainCamera.orthographicSize = Mathf.Clamp(newSize, minCameraSize, maxCameraSize); } else if (Input.GetAxis("Mouse ScrollWheel") < 0f) { float newSize = mainCamera.orthographicSize + zoomStep; mainCamera.orthographicSize = Mathf.Clamp(newSize, minCameraSize, maxCameraSize); } mainCamera.transform.position = clampCamera(mainCamera.transform.position); }
@thanhduyphan2234
@thanhduyphan2234 3 жыл бұрын
thank you so much
@DavidAdochiti
@DavidAdochiti 3 жыл бұрын
ty very very much
@Ffiree
@Ffiree 2 жыл бұрын
Works in mobile devices?
@bilgipaylasmplatformu8454
@bilgipaylasmplatformu8454 3 жыл бұрын
i want to use tilemap instead of sprite renderer, how can i do it?
@sanketvaria9734
@sanketvaria9734 3 жыл бұрын
will this work for 3D camera as well?
@ShackMan
@ShackMan 3 жыл бұрын
no, sorry.
@ShakerFS
@ShakerFS 3 жыл бұрын
You are amazing
@tyberius1313
@tyberius1313 2 жыл бұрын
Doing all that and then not explaining the last part really ruins what was a really a good video.
@indiandev1588
@indiandev1588 3 жыл бұрын
warning CS0649: Field `CameraZoomAnd2dMap.maxCamSize' is never assigned to, and will always have its default value `0' sir pls reply i have get this error
@indiandev1588
@indiandev1588 3 жыл бұрын
Sir pls reply
@darknside
@darknside 2 жыл бұрын
How to convert to the zoom wheel?
@lilbocheap139
@lilbocheap139 2 жыл бұрын
How are minCamSize and maxCamSize set? Since they're private it won't show in the inspector, right?
@ormar4564
@ormar4564 2 жыл бұрын
you can with the SerializeField, they appear in the Inspector
@kaiserium
@kaiserium 4 жыл бұрын
On a mobile device the camera jitters around when detecting multiple touches or if I tap around on the screen. Is there a simple solution to this issue? Thank you
@nustalljic8913
@nustalljic8913 4 жыл бұрын
Yooo I have the same problem. I've tried multiple tutoriakls here on youtube and they all have the same problem. The camera bounces around on mobile when you tap the screen making it unusuable. Game Dev Shack HELP USSSS!!!
@ShackMan
@ShackMan 4 жыл бұрын
I'll take a look at it tomorrow, I hadn't tried it on an actual mobile device yet. What exactly do you mean with multiple touches? like you put down two fingers as if you were going for a pinch and then the camera jumps between those 2 fingers?
@kaiserium
@kaiserium 4 жыл бұрын
@@ShackMan if you tap the screen repeatedly on either side the camera jitters dramatically and is unstable. Tap the left side of the screen and the right side of the screen quickly simultaneously for instance and you'll see the camera jitter. Thank you for getting back to me. If you can help solve this issue I would very much appreciate it
@ShackMan
@ShackMan 4 жыл бұрын
I've tried it out and it works fine for me... What you describe could be that the camera is bigger than the limits? In my example I'm using free aspect ratio, so depending on your phone the camera might be larger (either horizontal or vertical or both) than the sprite it is limited to. You could try to remove the limit or set the camera to be really small, then build the apk and try again. Let me know if it works!
@mauriciograsso8102
@mauriciograsso8102 3 жыл бұрын
¡gracias!
@alperakin2561
@alperakin2561 3 ай бұрын
Do anyone know how Can I do this with cinemachine camera
@softwarecprogrammieren
@softwarecprogrammieren Жыл бұрын
does it work in 3D? Your example is a plane (map)
@ShackMan
@ShackMan Жыл бұрын
The principal is the same, you check how much the mouse has moved and apply that to the camera, but you would have to adjust some stuff. For one 3D cameras are a lot more diverse than 2D cameras.
@disobedientdolphin
@disobedientdolphin Жыл бұрын
You really know you can trust someone if he uses 5 exclamation marks and two "1"s to make a point.
@hardcodednoob4645
@hardcodednoob4645 3 жыл бұрын
i tried the code, but why my camera is not moving? any help
@TheTrolderia
@TheTrolderia 3 жыл бұрын
It didn't work for me either. CHeck your code, it worked after i found out i missed private and big letter U in private void Update ;)
@fodk7021
@fodk7021 3 жыл бұрын
@@TheTrolderia it doesn't work tho and it can't work ScreenToWorldPoint takes a Vector3 not a Vector2
@foxzyx
@foxzyx 2 жыл бұрын
Problem you can’t press buttons when having this script active
@plusplusgames
@plusplusgames 2 жыл бұрын
did you figure out a fix
@lora6938
@lora6938 3 жыл бұрын
Please tell me how to make it smoothness? That there would be smoothness in the movement of the camera, that it would look alive
@SlitDiver
@SlitDiver 3 жыл бұрын
by probably creating a vector of the direction youre moving it and moving it with a delay using time.DeltaTime
@fodk7021
@fodk7021 3 жыл бұрын
Vector3.Lerp
@DevCoreFelix
@DevCoreFelix 2 жыл бұрын
@@fodk7021 Where do you put it?
@ahmed74kkk
@ahmed74kkk 3 жыл бұрын
i need to make the zoom with mouse wheel how ??
@thomasbjrnkrogh-jacobsen6391
@thomasbjrnkrogh-jacobsen6391 2 жыл бұрын
if (Input.GetAxis("Mouse ScrollWheel") > 0f) { ZoomIn(); } else if (Input.GetAxis("Mouse ScrollWheel") < 0f) { ZoomOut(); }
@AAAlexGames
@AAAlexGames 2 жыл бұрын
You are god
@Pretty_Ghost10
@Pretty_Ghost10 Жыл бұрын
camera cant move :(
@Pretty_Ghost10
@Pretty_Ghost10 Жыл бұрын
oh i change ortohgraphic camera fixed.
@quartal9588
@quartal9588 Жыл бұрын
@@Pretty_Ghost10 have you used the latest version of unity?
@quartal9588
@quartal9588 Жыл бұрын
nevermind, it started to work somehow
@cinemamovies1916
@cinemamovies1916 Жыл бұрын
didnt work
@lora6938
@lora6938 3 жыл бұрын
Eh😞 that would be like this for android (touchscreen)
@atomiz2002
@atomiz2002 3 жыл бұрын
red
@niqita_draws
@niqita_draws 2 жыл бұрын
Thank you!!!
Strategy Game Camera with Unity's New Input System
41:46
One Wheel Studio
Рет қаралды 31 М.
How to Make a Good 2D Camera
11:38
Game Maker's Toolkit
Рет қаралды 412 М.
This dad wins Halloween! 🎃💀
01:00
Justin Flom
Рет қаралды 45 МЛН
Random Emoji Beatbox Challenge #beatbox #tiktok
00:47
BeatboxJCOP
Рет қаралды 32 МЛН
Sigma baby, you've conquered soap! 😲😮‍💨 LeoNata family #shorts
00:37
Human vs Jet Engine
00:19
MrBeast
Рет қаралды 170 МЛН
Pinch to Zoom and Panning on Mobile in Unity
8:00
Press Start
Рет қаралды 31 М.
Building a Camera Controller for a Strategy Game
17:48
Game Dev Guide
Рет қаралды 196 М.
Isometric Game Tutorial - Pros and Cons, Art, Movement
11:16
Tamara Makes Games
Рет қаралды 130 М.
Drag & Move a Camera in Unity 2D | Bite-Sized Tutorials
4:35
chunky bacon games
Рет қаралды 10 М.
Camera Zoom in Unity with Cinemachine {Keyboard & Mouse}
5:56
Obsessive Games
Рет қаралды 29 М.
This dad wins Halloween! 🎃💀
01:00
Justin Flom
Рет қаралды 45 МЛН