Camera orthographic size certain width - unity3d

How do we can set a certain size of units for defining the width of the Orthographic size of the camera in the portrait mode?
I want to set the horizontal dimension to the 5 meters exactly from the center-left to the center-right of the screen for any mobile device? how can I achieve this? I've found this piece of code from a video clip but I don't understand it and I think it does not help me since I don't have a game field and also my game world will be generated automatically during the game (it's an infinite 2D scrolling game).
[SerializeField] private SpriteRenderer gameField;
void Start()
{
float screenRatio = (float)Screen.width / (float)Screen.height;
float targetRatio = gameField.bounds.size.x / gameField.bounds.size.y;
if (screenRatio > targetRatio)
{
Camera.main.orthographicSize = gameField.bounds.size.y / 2;
}
else
{
float differenceInSize = targetRatio / screenRatio;
Camera.main.orthographicSize = gameField.bounds.size.y / 2 * differenceInSize;
}
}
I don't know why unity doesn't handle these issues automatically?

I have found the video you have been talking about and it is actually pretty simple. For reference, it is this video. I will try to explain it to you.
These 5 boxes represent all content that you want to show on your screen. You want your camera to always adjust itself so it fits all of those boxes inside of it.
To archive this you have to multiply the width of our boxes (all of our boxes are 1 meter wide in all dimensions) by the screen height devided by the screen width. You then want to divide that number by two.
boxes.width * screen.height / screen.width * 0.5
In our code it looks like this:
public float sizeInMeters;
void Start()
{
float orthoSize = sizeInMeters * Screen.height / Screen.width * 0.5f;
Camera.main.orthographicSize = orthoSize;
}
If you want to have five meters to the left and right from the middle then put in 10 into the sizeInMeters variable. If your total screen width from left to right should only cover 5 meters you have to put in 5 into the sizeInMeters variable.
The if inside of your code is only there if you want the user to be able to flip his phone into a vertical position.

Related

Convert pixels to world space units

I'm planning to make my sprite dimension to be 1.5 inches to all devices. My problem now is convert the pixels to world space units so that I can scale my sprite correctly.
float pixelLength = Screen.dpi * 1.5f; // 1.5 inches
// code to convert pixelLength to world space units
float pixelLength = Screen.dpi * 1.5f;
// Using your sprite's pixel per unit...
float worldLength = pixelLength / spriteRenderer.sprite.pixelsPerUnit;
Alternatively, instead of scaling your sprites, you can change the Camera's OrthographicSize. Changing OrthographicSize works better if all of your sprites' PixelPerUnit are roughly the same, and you are scaling everything.

How to write dynamically to whole stencil buffer in Unity

What do I want to achieve ?
I'd like to achieve an effect in Unity3D, where I superpose a few cameras on top of each other. Each cameras would draw to a specific area of the screen. If possible, I'd like these areas to change dynamically.
I am using unity (latest version), and URP.
How technically I see it :
For implementation and performances reasons, it seems writing to the stencil buffer is the way to go. That way, I can only render what part of the screen I want for each camera. It is also quite easy once the stencil is made, cause the ForwardRendering settings in Unity offer such capabilities out of the box.
What I can't figure out :
The problem is, I don't know to efficiently write to the whole stencil buffer (each frame). The best way would be to use a compute shader (or maybe a simple script), that directly write the values after some calculations. Is there a way for that ? If yes, How ?
Another alternative may be to use a transparent quad in front of one of each camera, and to write to the stencil buffers like that. But 1) It seems there exist a SV_StencilRef keyword in the fragment buffer, but not supported by Unity yet ? 2) I will still lose performance nevertheless.
Thanks for any help / ideas about how to tackle this problem.
Edit (Clarification) : I'd like to be able to render free shapes, and not only rects, which prevent the use of the standard ViewportRect.
After some search, I found the Voronoi split screen to be quite similar (with a technical view) to what I'd like to achieve (See here)
If I understand correctly, you only need to play with the different camera Viewport Rect (https://docs.unity3d.com/ScriptReference/Camera-rect.html) to determine what camera should render what part of the screen.
Response to comment: no, it's not stretched. Here is an example with four cameras:
Create a scene with four cameras, add this script to it and add the cameras to the array on the script. I added the _movingObject just to see something moving, but it's not necessary.
using UnityEngine;
public class CameraHandler : MonoBehaviour
{
[SerializeField] private Transform _movingObject;
[SerializeField] private float _posMod = 10.0f;
[SerializeField] private float _cameraPosMod = 0.1f;
[SerializeField] private Camera[] _cameras;
private void Update()
{
float t = Time.time;
float x = Mathf.Sin(t);
float y = Mathf.Cos(t);
if (_movingObject) _movingObject.position = new(x * _posMod, 1.0f, y * _posMod);
Vector2 center = new(0.5f + x * _cameraPosMod, 0.5f + y * _cameraPosMod);
// bottom left camera
_cameras[0].rect = new(0.0f, 0.0f, center.x, center.y);
// bottom right camera
_cameras[1].rect = new(center.x, 0.0f, 1.0f - center.x, center.y);
// upper left camera
_cameras[2].rect = new(0.0f, center.y, center.x, 1.0f - center.y);
// upper right camera
_cameras[3].rect = new(center.x, center.y, 1.0f - center.x, 1.0f - center.y);
}
}
Not exactly an answer to your question about stencil buffer but I had a (hopefully) similar use case recently.
The main issue: In the URP Camera stack
If your camera is set to Base it will overdraw the entire screen
you can not adjust the Viewport on any Overlay camera
You can actually try to set the viewport via code -> result your camera renders only the correct part of the scene ... but it gets stretched to the entire screen ^^
What I did in the end was
Leave all content and cameras at the origin position
Apply according masks to filter the content per camera
Make your camera Overlay (as usual)
go through a custom Camera.projectionMatrix
m_Camera.projectionMatrix = Matrix4x4.Translate(projectionOffset) * Matrix4x4.Perspective(m_Camera.fieldOfView, m_Camera.aspect, m_Camera.nearClipPlane, m_Camera.farClipPlane);
where the projectionOffset is an offset in viewport space (normalized 0 - 1) from the bottom left corner.
For example in my case I wanted a minimap at 400, 400 pixels from the top-right corner so I did
var topRightOffsetPixels = new Vector2(400, 400);
var topRightOffsetViewport = Vector2.one - new Vector2(topRightOffsetPixels.x * 2 / Screen.width, topRightOffsetPixels.y * 2 / Screen.height);
m_Camera.projectionMatrix = Matrix4x4.Translate(topRightOffsetViewport) * Matrix4x4.Perspective(m_Camera.fieldOfView, m_Camera.aspect, m_Camera.nearClipPlane, m_Camera.farClipPlane);
See also Matrix4x4.Perspective

Moving camera to proper position in Zoom function in Unity

Hi I have a question that I'm hoping someone can help me work through. I've asked elsewhere to no avail but it seems like a standard problem so I'm not sure why I haven't been getting answers.
Its basically setting up a zoom function that mirrors Google Maps zoom. Like, the camera zooms in/out onto where your mouse is. I know this probably gets asked a lot but I think Unity's new Input System changed things up a bit since the 4-6 year old questions that I've found in my own research.
In any case, I've set up an parent GameObject that holds all 2D sprites that will be in my scene and an orthographic camera. I can set the orthographic size through code to change to zoom, but its moving the camera to the proper place that I am having trouble with.
This was my 1st attempt:
public Zoom(float direction, Vector2 mousePosition) {
// zoom calcs
float rate 1 + direction * Time.deltaTime;
float targetOrtho = Mathf.MoveTowards(mainCam.orthographicSize, mainCam.orthoGraphicSize/rate, 0.1f);
// move calcs
mousePosition = mainCam.ScreenToWorldPoint(mousePosition);
Vector2 deltaPosition = previousPosition - mousePosition;
// move and zoom
transform.position += new Vector3(deltaPosition.x, deltaPosition.y, 0);
// zoomLevels are a generic struct that holds the max/min values.
SetZoomLevel(Mathf.Clamp(targetOrthoSize, zoomLevels.min, zoomLevels.max));
previousPosition = mousePosition;
}
This function gets called through my input controller, activated through Unity's Input System events. When the mouse wheel scrolls, the Zoom function is given a normalized value as direction (1 or -1) and the current mousePosition. When its finished its calculation, the mousePosition is stored in previousPosition.
The code actually works -- except it is extremely jittery. This, of course happens because there is no Time.deltaTime applied to the camera movement, nor is this in LateUpdate; both of which helps to smooth the movements. Except, in the former case, multiplying Time.deltaTime to new Vector3(deltaPosition.x, deltaPosition.y, 0) seems to cause the zoom occur at the camera's centre rather than the mouse position. When i put zoom into LateUpdate, it creates a cool but unwanted vibration effect when the camera moves.
So, after doing some thinking and reading, I thought it may be best to calculate the difference between the mouse position and the camera's center point, then multiply it by a scale factor, which is the camera's orthographic size * 2 (maybe...??). Hence my updated code here:
public void Zoom(float direction, Vector2 mousePosition)
{
// zoom
float rate = 1 + direction * Time.unscaledDeltaTime * zoomSpeed;
float orthoTarget = Mathf.MoveTowards(mainCam.orthographicSize, mainCam.orthographicSize * rate, maxZoomDelta);
SetZoomLevel(Mathf.Clamp(orthoTarget, zoomLevels.min, zoomLevels.max));
// movement
if (mainCam.orthographicSize < zoomLevels.max && mainCam.orthographicSize > zoomLevels.min)
{
mousePosition = mainCam.ScreenToWorldPoint(mousePosition);
Vector2 offset = (mousePosition - new Vector2(transform.position.x, transform.position.y)) / (mainCam.orthographicSize * 2);
// panPositions are the same generic struct holding min/max values
offset.x = Mathf.Clamp(offset.x, panPositions.min.x, panPositions.max.x);
offset.y = Mathf.Clamp(offset.y, panPositions.min.y, panPositions.max.y);
transform.position += new Vector3(offset.x, offset.y, 0) * Time.deltaTime;
}
}
This seems a little closer to what I'm trying to achieve but the camera still zooms in near its center point and zooms out on some point... I'm a bit lost as to what I am missing out here.
Is anyone able to help guide my thinking about what I need to do to create a smooth zoom in/out on the point where the mouse currently is? Much appreciated & thanks for reading through this.
Ok I figured it out for if anyone ever comes across the same problem. it is a standard problem that is easily solved once you know the math.
Basically, its a matter of scaling and translating the camera. You can do one or the other first - it does not matter; the outcome is the same. Imagine your screen looks like this:
The green box is your camera viewport, the arrow is your cursor. When you zoom in, the orthographic size gets smaller and shrinks around its anchor point (usually P1(0,0)). This is the scaling aspect of the problem and the following image explains it well:
So, now we want to move the camera position to the new position:
So how do we do this? Its just a matter of getting distance from the old camera position (P1(0, 0)) to the new camera position (P2(x,y)). Basically, we only want this:
My solution to find the length of the arrow in the picture above was to basically subtract the length of the cursor position from the old camera position (oldLength) from the length of the cursor position to the new camera position (newLength).
But how do you find newLength? Well, since we know the length will be scaled accordingly to the size of the camera viewport, newLength will be either oldLength / scaleFactor or oldLength * scaleFactor, depending on whether you want to zoom in or out, respectively. The scale factor can be whatever you want (zoom in/out by 2, 4, 1.4... whatever).
From there, its just a matter of subtracting newLength from oldLength and adding that difference from the current camera position. The psuedo code is below:
(Note that i changed 'newLength' to 'length' and 'oldLength' to 'scaledLength')
// make sure you're working in world space
mousePosition = camera.ScreenToWorldPoint(mousePosition);
length = mousePosition - currentCameraPosition;
scaledLength = length / scaleFactor // to zoom in, otherwise its length * scaleFactor
deltaLength = length - scaledLength;
// change position
cameraPosition = currentCameraPosition - deltaLength;
// do zoom
camera.orthographicSize /= scaleFactor // to zoom in, otherwise orthographic size *= scaleFactor
Works perfectly for me. Thanks to those who helped me in a discord coding community!

Physics functions with different resolutions(Unity)

I have my scripts:
Collider2D[] hitColliders = Physics2D.OverlapCircleAll(vector 2 pos, float radius);
I need to get all colliders from point(pos) with radius half of Screen.width with different screen resolution. How can I give these parameters (pos and radius) to this function?
playerObject.GetComponent<Rigidbody2D> ().AddForce (new Vector2 (direction.x * powerMultipl,direction.y * powerMultipl), ForceMode2D.Impulse);
The same thing! I want to scale my force depending on screen resolution!
All I need is my game to be played in the same way on devices with different screen resolution! Thnx for helping me!
Always be careful about screen space and world space the Physics2D.OverlapCircleAll() function takes all the parameter with respect to world space (Cartesian coordinate) so first convert screen space to world space using
Camera.main.ScreenToWorldPoint(ScreenCoordinate) // returns a vector3
you also have to convert Screen.width into world units , check below
http://answers.unity3d.com/questions/736142/what-is-good-practice-to-set-pixels-to-units-to-an.html

Position auto-scaled UI element with Camera.WorldToScreenPoint [duplicate]

This question already has answers here:
UI Canvas Image with UI Buttons
(2 answers)
Closed 9 months ago.
I've got a Canvas.
I'm creating some Text elements right above 3D objects in the scene with this code:
Vector3 screenPos = Camera.main.WorldToScreenPoint(this.dices[x, z].transform.position);
screenPos.x -= 25;
screenPos.y += 10;
newScoreItem.GetComponent<RectTransform>().anchoredPosition = screenPos;
On Android my UI elements are tiny so I set the surrounding Canvas` UI Scale Mode to "Scale with screen size".
The problem is that the position I determine with the code above doesn't match the one of scaled canvas. My Text elements are scaled but at the completely wrong location.
How may I solve that problem?
Correct positioning (on Mac):
Wrong positioning (somewhere out of the screne) with Scale with screen size(on Android):
First check Anchors Min/Max of the Text "newScoreItem": point 0,0 on the screen is in the bottom left corner, so Anchors Min/Max should be 0 (bottom left).
Second - it matters how did you set Screen Match Mode.
If it is set to match width or height you can use the following script:
float refWidth = 800f; // reference resolution - width - set in Canvas Scaler
float refHeight = 480f; // reference resolution - height - set in Canvas Scaler
bool matchWidth = true; //true if screen match mode is set to match the width,
//false if is set to match the height
Vector3 screenPos = Camera.main.WorldToScreenPoint(this.dices[x,y].transform.position);
if (matchWidth) {
screenPos.x *= refWidth / Screen.width;
screenPos.y *= refWidth / Screen.width;
} else {
screenPos.x *= refHeight / Screen.height;
screenPos.y *= refHeight / Screen.height;
}
screenPos.x -= 25f;
screenPos.y += 10f;
newScoreItem.GetComponent<RectTransform>().anchoredPosition = screenPos;
It works for me, although maybe there is easier way to do it.