Unity 2D Android - Restrict object to within the screen - unity3d

I am working on a 2D Game similar to Space Shooter. I developed it for Web and PC and it works great. I am now porting it to Android and am having an issue with the Player code.
The player(a space ship) will be at the bottom of the screen and it moves left to right within the screen. I wrote a piece of code which limits the player within the screen and here is the code:
private float screenx = Screen.width -20;
playerPosScreen = Camera.main.WorldToScreenPoint(transform.position);
if(Input.GetKey(KeyCode.RightArrow) && playerPosScreen.x < screenx)
{
transform.Translate(Vector3.right * speed * Time.deltaTime * 0.4f);
}
if (Input.GetKey(KeyCode.LeftArrow) && playerPosScreen.x > 20)
{
transform.Translate(-Vector3.right * speed * Time.deltaTime * 0.4f);
}
I am aware that I still need to convert few of the static values in the above code and this is is not really a good way to code.
My question here is how do I do this in Android? I want the player to stay in the screen, i.e if the user moves the player by dragging him to extreme left, no matter how much ever he tries to drag, the player should stay at the left corner of the screen and the same applies to right. In simple terms I want to detect the left and right edges of the screen and limit my object within these edges.
My game will be in landscape mode.
Any help would be very much appreciated. Thanks in advance.

This sort of problem is generally solved in the following manor:
if(transform.position.x < screenx) {
transform.position.x = screenx;
}
Here, we are checking to see if the transformed player is out of the screen space. If it is, we set it to the minimum it can be - which I am assuming is screenx.

public Transform player;
public float distanceFromCamera=10;
public float offsetx=.05f;
public float offsety=.05f;
void Awake()
{
player.position=Camera.main.ViewportToWorldPoint(new Vector3(offsetx,offsety,distanceFromCamera));
}
this will be your bottom left screen boundry

Related

Unity2D - On build, the background is shorter than it should be

While in editor, everything's working fine, but when I build the game to my phone, the background seems to be short on top and bottom side.
This is a screenshot from the phone build.
This is a screenshot from Unity.
I checked all sizes and they were all the same - 800x1280. I think the problem started to happen when I made the cloudy background infinitely move with a quad.
Checked everywhere, can't seem to pin-point the problem.
You should resize the background according to screen size. You can do that through code. If you are using Sprite Renderer, you can follow this link to do so. Here's the main codes needed to resize a sprite according to the above link.
void Awake() {
SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();
float cameraHeight = Camera.main.orthographicSize * 2;
Vector2 cameraSize = new Vector2(Camera.main.aspect * cameraHeight, cameraHeight);
Vector2 spriteSize = spriteRenderer.sprite.bounds.size;
Vector2 scale = transform.localScale;
if (cameraSize.x >= cameraSize.y) { // Landscape (or equal)
scale *= cameraSize.x / spriteSize.x;
} else { // Portrait
scale *= cameraSize.y / spriteSize.y;
}
}
Or if you are using a UI Panel under Canvas to draw the background, you can set the anchors on the edge points and set the Canvas's UI Scale Mode to Scale With Screen Size

how to get background to scroll with player height in unity?

I am making an endless jumper. I am trying to get the BG to scroll down based on the players height.
I have seen code that moves the code at a specific speed:
public float speed = .5f;
void Updated(){
Vector2 offset = new Vector2(0, Time.deltatime * speed);
GetComponent<Renderer>().material.mainTextureOffset = offset;
}
I want to move it with the height of the player.
public float PlayerHeight;
So now I need to set the height of the BG. I can't figure out how to do this part.
Transform background;
public float backgroundHeightY;
public GameObject BackGround;
from here I am stuck. I don't want it to move with the camera, but move at a certain rate based on the height of the player. Any help would be awesome.
It sounds like you have a background that has a fixed position relative to the camera, but you want the background to scroll "against" the player as they move up and down, giving a parallax effect?
public Transform player;
public float multiplier = 0.1f; //Tweak this
void Update(){
Vector2 offset = new Vector2(0, player.position.y * multiplier);
GetComponent<Renderer>().material.mainTextureOffset = offset;
}
I have it working well going up, but not down. Here is how it is working going up. I have adjusted the backgroundModifier to fit the timing I need.
//Changes the BG position
changeAmount = (playerHeightY - currentCameraHeight)/backgroundModifier;
Vector3 temp = new Vector3(0, changeAmount, 0);
BackGround.transform.position += temp;
Anyone have an idea on how to get the falling to work. I feel like I am making this harder than it needs to be.
Here is how I finally did this. I actually switched the camera from orthographic to perspective. It took a lot of tweaking to layout, but it ended up working perfectly well. So the code I have above I deleted.

How can i turn the camera to left and right in unity for a sphere?

updated CODE .. the problem is that i cant move the ball only if i hold the E button than i use WASD or arrows to move the ball...and when i hold Q the camera 2 activates and i can move the ball with WASD or arrows...but with the right axis for that angle...is like ballance that game... i want to not hold the E or Q just to change the camera and move the ball corecctly for that angle with the right axis for the ball but not holding the cameras button
using UnityEngine;
using System.Collections;
public class controlPlayer : MonoBehaviour {
public float viteza ; // this is speed
;
void Start(){
}
void Update()
{
if(Input.GetKey(KeyCode.Q) ) // if i hold Q the camera 2 activates and with WASD i can move the ball
{
float miscaOrizontal = Input.GetAxis("Horizontal");
float miscaVertical = Input.GetAxis("Vertical");
Vector3 miscare = new Vector3(miscaVertical,0.0f,(-miscaOrizontal)); //also here i chande the axis for the camera 2
rigidbody.AddForce(miscare * viteza * Time.deltaTime);
}
if(Input.GetKey(KeyCode.E) ) // here when i press E the camera 1 activates and alos i can move the ball if i keep pressing E
{ float miscaOrizontal2 = Input.GetAxis("Horizontal");
float miscaVertical2 = Input.GetAxis("Vertical");
Vector3 miscare2 = new Vector3(miscaOrizontal2,0.0f,miscaVertical2); // here are the controls for the ball for the camera ..i had to change the axis here..
rigidbody.AddForce(miscare2 * viteza * Time.deltaTime);
}
}
}
}
Alright, so if I'm understanding you correctly, you want the ball to move in relation to which direction the camera is currently facing. As well as you don't want to have to hold down "Q" or "E" while you move your ball with WASD controls.
So there are a few things that I'd like to mention here, so we'll take them one at a time. First off, you shouldn't have "AddForce" inside of an Update call. Update is called every frame whenever it can. It's great for input, but generally you want to call it in "FixedUpdate" instead. It provides a better response across many devices. If you leave it in update, you can get inaccurate physics results, and missed collisions. There's a lot out there on this subject, so if you want to know more about it, then just google for a little while.
As for the code side, you want to store a reference to what camera you're using to avoid having to hold these buttons down.
What I mean is:
private Camera referencedCamera = null;
private void Start()
{
referencedCamera = camera1;
}
private void Update()
{
if(Input.GetKey(KeyCode.Q)) referencedCamera = camera2;
else if(Input.GetKey(KeyCode.E)) refrencedCamera = camera1;
}
This way you can reference which camera is being used, rather than a key input. Something else to look into is the "State Design Pattern". Below is a video over the "State Design Pattern." That is a great video tutorial series that Derek Banas put up on design patterns, extremely recommend watching them, but the state pattern could potentially solve this problem for you as well. So that should take care of not having to hold the button down in order to make the move. More or less, the buttons will now allow you to just switch which camera is currently being used.
https://www.youtube.com/watch?v=MGEx35FjBuo
So now that that is solved, you want to transform the input that you currently have, and you want to put it in terms of hte camera that is currently being used. So to avoid rewriting a lot of the code over and over again, just know that these two code snippets should be pieced together into one. So "referencedCamera" should be already defined in the code I'm about to write:
private void FixedUpdate()
{
if(referencedCamera != null)
{
float miscaOrizontal = Input.GetAxis("Horizontal");
float miscaVertical = Input.GetAxis("Vertical");
Vector3 miscare = referencedCamera.transform.TransformDirection(
new Vector3(miscaVertical, 0.0f, -miscaOrizontal));
rigidbody.AddForce(miscare * viteza * Time.deltaTime);
}
}
So now with this, is it's the same code, but there is a call to the referenced cameras transform to take the vector 3 from the input and put it in relation to the camera instead, and add the new relational vector to the object.
I also want to recommend you looking into events rather than if checks in the update function, but that is beyond the scope of the question. Hope this helps and any questions, don't hesitate to ask.
EDIT
After further discussion, we came across something that should also be mentioned. If your camera that you are referencing is angled, the force will be applied in that angle, so keep that in mind. If it is pointed towards an object downward, then forward relative to the camera will apply a force downward, and not entirely in what you may consider the forward direction. Thought it was worth mentioning.

Unity - Walk around a cube

I have an issue with trying to get an 'object(character)' to walk around a cube (all sides) within Unity. Ive attached an image and video showing what i am trying to achieve. Im trying to show you visually rather than trying to explain. As the character drops over the edge it rotates 90 degrees and then the stands up like gravity has switched. Then the character can jump walk etc.
This is an example of someone else that posted a video showing exactly what im trying to achieve
I have looked through the forums and cant find what im after. i have tried to attach a diagram but the site wont let me. Any advice would be greatly appreciated!
Regards
Nick
You have a couple of options that I can think of.
One is to trigger the gravity change when the character exits one face of the cube to go to another. To achieve this you would have trigger zones on each edge and face and use a [Bob went from Face A to Edge ANorth -> Switch Gravity to go in X direction].
This would work for situations where the gravity switch must affect other objects too but be advantageous to your player (walking off the side makes an enemy fall off and die - for example.)
However, if you want all entities to stick to their relative sides then we need to make custom gravity! To do this is easier than you might think as gravity is simply a downward accelleration of 9.8. So turn off the engines native gravity and create a "personal gravity" component:
private Vector3 surfaceNormal;
private Vector3 personalNormal;
private float personalGravity = 9.8f;
private float normalSwitchRange = 5.0f;
public void Start()
{
personalNormal = transform.up; // Start with "normal" normal
rigidbody.freezeRotation = true; // turn off physics rotation
}
public void FixedUpdate()
{
// Apply force taking into account character normal as personal gravity:
rigidbody.AddForce(-personalGravity * rigidbody.mass * personalNormal);
}
Rotating your character and changing his normal is then up to you to suit your situation or game mechanic, whether you do that by raycasting if you're standing on a surface to detect when to change it or only want gravity to change when you hit a powerup or similar - experiment and see what works. Comment more if you have questions!
EDIT:
As an addition to the video you linked. You can keep a state variable on the jump state and raycast in each axis direction to check which face is nearest in the case of just rolling off.
public void Update()
{
// we don't update personal normals in the case of jumping
if(!jumping)
{
UpdatePersonalNormal();
}
}
public void UpdatePersonalNormal()
{
RaycastHit hit; //hit register
// list of valid normals to check (all 6 axis)
Ray[] rays =
{
Vector3.up, Vector3.down,
Vector3.left, Vector3.right,
Vector3.forward, Vector3.backward
};
//for each valid normal...
foreach(Ray rayDirection in rays)
{
//check if we are near a cube face...
if(Physics.Raycast(rayDirection , hit, normalSwitchRange)
{
personalNormal = hit.Normal; //set personal normal ...
return; // and return as we are done
}
}
}
Please keep in mind that the above is completely hand written and not tested but play with it and this pseudo start should give you a good idea of what to do.

visual lag of the moving picture in Unity3D. How to make it smoother?

I make a game in Unity3D (+2D ToolKit) for iOS.
It is 2d runner/platformer with side view. So on screen is moving background and obstacles. And we control up/down the main character to overcome obstacles.
The problem is that the moving picture has a visual lag. In other words, it moves jerkily or creates the tail area of the previous frames on iOS-devices. In XCode the number of frames is 30 and over.
I have objects 'plain' with the following script:
public class Move: Monobehavior
{
private float x;
public float Speed = 128.0f;
void Start()
{
x = transform.position.x;
}
void Update()
{
x += Time.DeltaTime *Speed;
Vector3 N = transform.position;
N.x = mathf.FloorInt(x);
transform.position = N;
}
}
The question is how to make the move of background smoother, without jerks and flicker on screen while playing? Maybe the problem is in framerate parameter.
Can anybody help me to find a solution?
I'd say it's the use of the FloorInt function which will move the background only in steps of 1 which is rather not smooth. It should get better when you comment that line out. Do you have any special reason why you are doing the FloorInt there?
The use of floor will definitely hurt your performance. Not only is it one more thing to calculate, but it is actually removing fidelity by removing decimals. This will definalty make the movement look 'jerky'. Also, update is not always called on the same time inteval, depending on what else is happening during that frame, so using Time.delaTime is highly recommended. Another thing, you do not need to set variables for x and Vector3 N, when you can update the transoms position like the code below. And if you have to, you sill only need to create one variable to update, and set your position to it. The code below just updates the players x position at a given rate, based on the amount of time that has passes since the last update. There should be no 'jerky' movement. (Unless you have a serious framerate drop);
public class Move: Monobehavior
{
public float Speed = 128.0f;
void Update()
{
transform.position =
(transform.position.x + (speed*Time.DeltaTime),
transform.position.y,
transform.position.z);
}
}