How do I make so when user moves the camera it doesn't go beyond the scene borders? - c#

How do I make so when I move the camera(with touch) it doesn't go beyond the scene borders?
How do I move the camera with touch so it moves strictly with scene parts, like slides(swipe-first slide, another swipe-another slide) with not going beyond the borders of the scene?
The game I'm making has a camera like in Disco Zoo game for android (I'm a newbie)

Technically, the scene doesn't really have a border. You'll need to define the border somehow within your game, then constrain the camera's position with something like Mathf.Clamp(value, min, max) in an Update() function on the camera.
How can you define the border? It's up to you. Some ideas:
Hard-code the values in the script that clamps the camera. Probably the quickest option, but not flexible
Make public parameters on the camera script that let you set min and max positions in the X and Y directions
If you have a background image: use the extents of that to define your camera's extents
Create empty objects in your scene that define the minimum and maximum extents of the scene. Put your "min" object at the top-left, and the "max" object at the top-right. Connect it to the camera script, then use those positions to see if you've gone too far in any given direction. The main reason to do this is that it's visual.
(Slower, but dynamic) If everything in your scene uses physics, you could search the entire scene for every Collider component, then find the furthest extents in each direction. However, this is probably going to be pretty slow (so you'll only want to do it once), it'll take a while to code, and you'll probably want to tweak the boundaries by hand anyway.

Related

Distance between game object and ground in Unity

I recently started having a look at game development with Unity and was trying to make a simple 2D character with basic movement abilities. This character is supposed to jump and move from side to side, but only if it is standing on something.
Now my question is: How do you check if a player is standing on something? / Get the distance to the next game object / collider beneath the player game object?
Would greatly apreciate any helpful answers and especially explanations on how exactly it works. Thanks!
To do this, you need to send a ray to detect the point of impact on the ground and then calculate the distance. The code below sends a ray from the center of your object down to the maximum height (3) and gives the size.
public LayerMask groundLayer;
public float maxRayLength = 3;
public void Update()
{
var hit = Physics2D.Raycast(transform.position, Vector3.down, maxRayLength, groundLayer.value);
if (hit) Debug.Log(hit.distance); // it will print current distance from pivot
}
If you want to calculate the height of the ray from the character's foot, there are two methods, one is subtracting half the height of the character from it.
Physics2D.Raycast(transform.position-transform.up*height, ....)
Next one is to use an empty object at the base of the character, which we refer to instead of the center.
public Transform pivot;
Then..
Physics2D.Raycast(pivot, ....)
There are a few ways of actually doing this.
The most usual although a bit complicated way of doing it for a beginner is using Raycasts. A Raycast is basically a small invisible line that starts and ends where you tell it to. If anything of a specific tag or layer is caught in it's crossfire you can basically pull that object from your code. Raycasts are used for a lot of things, most notably in Shooter games to shoot or in games like Skyrim to pickup objects and interact with them.
Another way to do this, which is a bit more popular in 2D games is to create a "feet" GameObject and make it the child of the player in the hierarchy. You can add a box collider on that GameObject and check the "IsTrigger". You can add a Tag to your ground objects and through your code using the OnTriggerEnter() and OnTriggerExit() Methods you can basically tell when your character is floating on air and when he is on ground.
Another popular method is to use the Physics.OverlapBox() Method which is pretty much the same as the Trigger Method but you are creating an invisible box (much like a raycast) and instead of only getting notified when Triggered (something enters or exits) you check if the invisible box is colliding with another object/tag/collider (which could be your ground).
There are also a few different things you can do with a Nav Mesh (mostly in 3D) but I think that for now these 3 should suffice!

Can't Make animation for only Z axis in uniy

I have a quick question. If anyone can answer me, I will be grateful. I want to make an animation for about 117 cubes. I know that I don't need to do it one by one. I can simply make a prefab for the cube and duplicate it, but the problem is I just want to make it for the z-axis. However, the animation applies it for all the position properties. So how can I make an animation for the z-axis without affecting y and x? Thank you.
The problem is that you are animating the cubes based on the world position, so it is teleporting everything even for x axis and y axis.
You can easily avoid this by adding your prefab with the animation inside an empty gameObject, you can save it as a prefab too. In this way when you instantiate the empty with inside the cube, the child object (your cube) will move based on the empty position, so y and x will be the x and y of the empty one.
So
1 animate your cube
2 add the cube to an empty game Object
3 set your empty as prefab and duplicate it
If your animation is not sprite based, only transform based, you can use TWEENING Libraries. LeanTween is in the Unity Asset Store as free asset. It is far much faster than builtin unity animation. It is really easy to use. I used it in over 100 UI objects and it didn't even used any remarkable resource at all (FOR 2D Object). I believe that will solve your problem easily.

Set limit camera screen WITDH

Look my game has a fixed camera, configured as a standard 1280x720.
I placed at each end of the cam width of an empty object with a collider to prevent the player pass this point.
Everything works perfectly until the default resolution decreases. When I run the test with 480x320 screen width decreases, but the collider, does not follow this decrease, staying out of the screen, which makes the player to be "cut off."
The following two images:
First: 1280x720
Second: 480x320
There is some way which I can only set the side margins left and right of the camera as a collider?
If it is not possible to configure only the edge of the camera as a delimiter, the player would have some other way to do something to solve my problem?
Some items fall from the sky, so I can not have a collider at the top of the camera.
There are many ways to do this. The easiest way is to create a 4 box collider 2D and position them to the edge of the screen.
I always use this complete script to do this. It's too long to post here. Just attach it to an empty GameObject in the scene. It will do the rest of the work for you. I will create the colliders and position them to the edge of the scrren automatically.
As what i have understand my be this can help you
Scale box collider to camera view

Object-following Virtual Buttons

As shown in the picture, I want to be able to maintain this placement of virtual buttons wherever the ball moves.
This is what I've tried:
1.
The cue ball is a Rigidbody with Bounce Material, so it can bounce off the cushions. So in this case, I tried making the Virtual Buttons RigidBody Components and adding the same force to the buttons, but this didn't work because it wasn't able to detect the cushions and kept moving forward.
2.
I gave it a collider, it would bounce off the cushion before the ball and that would disrupt the formation around the ball.
3.
I tried to parent the Virtual Buttons under the Cue Ball and the Cue Ball under the Image Target, but this didn't help since it all centered within the ball and overlapped. I couldn't move it at all (I don't know why)
Willing to put a Bounty on the answer.
Virtual Butttons sometimes don't move above the Image Target, I really don't know why. But here's a work around.
Now consider your CueBall the parent. Throw in 8 Empty GameObjects as child Objects. Position these GameObjects in the position around the ball that you wish to maintain through the movement.
Now each virtual button is put as a child to these GameObjects respectively.
And now script movement of the ball. You should see it works perfectly. Make sure you have your X and Z rotation restriction. I guess since it's a Cue ball and its white, the rotation won't be much of a problem, unless you're scripting for Curve shots as well.
Hope this helps.
A solution might be to create a script to attach to your ImageTarget, that has 9 public transforms, (your 8 planes and the cue ball) that would then look at the cue ball's x and z coords, and then would change the planes' x and z coords accordingly.

How to make scroll map in XNA (2D)?

I have a map, containing many objects in an area sized 5000*5000.
my screen size is 800*600.
how can i scroll my map, i don't want to move all my objects left and right, i want the "camera" to move, But unfortunately i didn't found any way to move it.
Thanks
I think you are looking for the transformMatrix parameter to SpriteBatch.Begin (this overload).
You say you don't want the objects to move, but you want the camera to move. But, at the lowest level, in both 2D and 3D rendering, there is no concept of a "camera". Rendering always happens in the same region - and you must use transformations to place your vertices/sprites into that region.
If you want the effect of a camera, you have to implement it by moving the entire world in the opposite direction.
Of course, you don't actually store the moved data. You just apply an offset when you render the data. Emartel's answer has you do that for each sprite. However using a matrix is cleaner, because you don't have to duplicate the code for every single Draw - you just let the GPU do it.
To finish with an example: Say you want your camera placed at (100, 200). To achieve this, pass Matrix.CreateTranslation(-100, -200, 0) to SpriteBatch.Begin.
(Performing a frustum cull yourself, as per emartel's answer, is probably a waste of time, unless your world is really huge. See this answer for an explanation of the performance considerations.)
Viewport
You start by creating your camera viewport. In the case of a 2D game it can be as easy as defining the bottom left position where you want to start rendering and expand it using your screen resolution, in your case 800x600.
Rectangle viewportRect = new Rectangle(viewportX, viewportY, screenWidth, screenHeight);
Here's an example of what your camera would look like if it was offset off 300,700 (the drawing is very approximate, it's just to give you a better idea)
Visibility Check
Now, you want to find every sprite that intersects the red square, which can be understood as your Viewport. This could be done with something similar to (this is untested code, just a sample of what it could look like)
List<GameObject> objectsToBeRendered = new List<GameObject>();
foreach(GameObject obj in allGameObjects)
{
Rectangle objectBounds = new Rectangle(obj.X, obj.Y, obj.Width, obj.Height);
if(viewportRect.IntersectsWith(objectBounds))
{
objectsToBeRendered.Add(obj);
}
}
Here's what it would look like graphically, the green sprites are the ones added to objectsToBeRendered. Adding the objects to a separate list makes it easy if you want to sort them from Back to Front before rendering them!
Rendering
Now that we found which objects were intersecting we need to figure out where on the screen the will end up.
spriteBatch.Begin();
foreach(GameObject obj in objectsToBeRendered)
{
Vector2 pos = new Vector2(obj.X - viewportX, obj.Y - viewportY);
spriteBatch.Draw(obj.GetTexture(), pos, Color.White);
}
spriteBatch.End();
As you can see, we deduce the X and Y position of the viewport to bring the world position of the object into Screen Coordinates within the viewport. This means that the small square that could be at 400, 800 in World Coordinates would be rendered at 100, 100 on the screen given the viewport we have here.
Edit:
While I agree with the change of "correct answer", keep in mind that what I posted here is still very useful when deciding which animations to process, which AIs to update, etc... letting the camera and the GPU make the work alone prevents you from knowing which objects were actually on screen!

Categories