Unity 2D Android Limit GameObject transform horizontal - unity3d

Is there a way to limit the transform of a game object on the x axis? I am using GUI Textures as buttons to slide a game object right and left, but I don't want to it to slide outside of the screen view. Any advice is appreciated.
public float moveSpeed = 0.5f;
void Update () {
float horiz = Input.GetAxis ("Horizontal");
transform.Translate(new Vector3(horiz * moveSpeed,0,0));
}

You can use the Mathf.clamp() method.
Example:
float xPos = Mathf.clamp(xPos, minX, maxX);
This makes sure that if xPos goes below minX it will be set to minX and if it goes above maxX it will be set to maxX meaning that xPos can never be higher than maxX or lower than minX.

A simple way is to put game objects (ex. cube) as boundary of the screen. That way, you cant move your game object outside the screen, because it will collide with the boundary and stop going outside the screen.

Related

How can I stop getting mouse position of UI Elements in Unity2D?

I'm making a mobile game where there is a simple circle with a handle attached to it, it can be controlled and can be rotated with mouse position, I'm using below code for handle control.
public class Controller : MonoBehaviour
{
private float m_force = 0.04f;
// amount of force for the player (circle and handle both)
public GameObject firePoint; // It is the tip of the handle which will shoot bullets
public float senstivity = 1f;
// senstivity control
public void ControlSenstivity(float index)
{
senstivity = index;
}
void Update()
{
//Get the Screen positions of the object
Vector2 positionOnScreen = Camera.main.WorldToViewportPoint(transform.position) ;
//Get the Screen position of the mouse
Vector2 mouseOnScreen = Camera.main.ScreenToViewportPoint(Input.mousePosition) ;
//Get the angle between the two points
float angle = AngleBetweenTwoPoints(positionOnScreen, mouseOnScreen) ;
// it will control the rotation of player (circle and handle both)
transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, angle) * senstivity);
}
float AngleBetweenTwoPoints(Vector3 a, Vector3 b)
{
return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg ;
}
// Below function for adding force to the player (both the circle and the handle), this function I added for mobile input whenever the button is pressed
public void AddForce()
{
transform.Translate(-firePoint.transform.localPosition.x, 0, 0 * m_force);
}
}
In this mobile game the user can rotate the player by dragging on the screen and can move the player by exerting force in the opposite direction of fire point whenever the add force button is pressed but the problem is that whenever I press the button the player takes Input.mousePosition of that button position and get rotated towards the button, that's why it will always move in one direction that is opposite of button. I wanted to know what can I do to not get Input.mousePosition of button which is in the canvas and can originally get position only of camera space. Any response will be appreciated, Thanks in advance!
You can use EventSystem.IsPointerOverGameObject. This method will check if your pointer(mouse/joystick) is on any of the UI elements.
Add if condition before getting mouse position.
// This will ignore all UI game objects
if (!EventSystem.current.IsPointerOverGameObject())
{
//Get the Screen positions of the object
Vector2 positionOnScreen = Camera.main.WorldToViewportPoint(transform.position);
}

Enemy does not look in upward direction when the player is at height

enemy not looking at the player standing at height my enemy does not look in the upward direction while shooting when the player is standing at the height i used these two methods but none of them making the enemy look towards the player when the player is at some height , im also adding the picture to make it clear
First method :
transform.LookAt (ThePlayer.transform.position);
Seond method:
Vector3 direction = ThePlayer.transform.position - transform.position;
direction.y = 0;
if (direction.x != 0 && direction.z != 0) {
transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation
(direction), 1.5f * Time.deltaTime);
transform.eulerAngles = new Vector3 (0, transform.eulerAngles.y, 0);
Yeah on Draco18s's post, you should try moving the enemy's head with Tranform.LookAt(myplayer.trasform.position) however note that the enemy will look at the player's pivot point, so if the player's pivot point is at their feet, that is where the enemy will look.
Best of luck.

Orbiting target with camera and changing height

I want to be able to use joystick (left-right) to make the camera orbit around target. I have this handled with the code below:
using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;
public class OrbitCamera : MonoBehaviour {
public Transform target;
public float turnSpeed;
public float height;
public float distance;
private Vector3 offsetX;
void Start()
{
offsetX = new Vector3 (0, height, distance);
}
void LateUpdate()
{
offsetX = Quaternion.AngleAxis (CrossPlatformInputManager.GetAxis ("hOrbit") * turnSpeed, Vector3.down) * offsetX;
transform.position = target.position + offsetX;
transform.LookAt (target.position);
}
}
I need to extend this script so that the player can move camera also up and down using the same joystick. So what I want is the camera to be able to move around player in a shape of sphere, always looking at the player. Thanks in advance.
Use a boom camera
A boom camera is wonderfully easy to setup and has a range of convenient cinematic controls:
To set it up, you simply create a new game object which we'll call the dolly. You then simply parent the camera to the dolly and tidy up the positions and rotations:
Camera
Transform: 0,0,-distance
Rotation: 0,0,0
Dolly
Transform: 0,height,0
Rotation: 0,0,0
Why a boom camera is great
Rotate the dolly on x and y and you'll get the camera moving in a sphere. (Note that dragging the rotation gizmo in scene view doesn't show the effect properly because of axis alignment; edit the x/y rotation values in the inspector only).
That -distance z value is the zoom. Change the local position of the camera to zoom in/out.
Local rotating the camera gives interesting tilt/pan effects.
Making it work in your case
You'd attach the script to the dolly gameobject, then use the joystick input to rotate it on x/y:
using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;
public class OrbitCamera : MonoBehaviour {
// Height and distance are now set in the scene (by positioning the dolly and changing that camera z value).
public float turnSpeed;
private float horizontal;
private float vertical;
void LateUpdate()
{
// Update horizontal/ vertical angles:
horizontal += CrossPlatformInputManager.GetAxis ("hOrbit") * turnSpeed;
vertical += CrossPlatformInputManager.GetAxis ("vOrbit") * turnSpeed;
// Update the rotation:
transform.rotation = Quaternion.Euler(horizontal, vertical, 0f);
}
}

Player & Enemy 2D auto-rotation

I have a player at the bottom of the screen, and an enemy at the top of the screen. I want them both to continuously rotate towards each other. Here is my code for both:
void Update ()
{
Vector3 diff = target.position - transform.position;
diff.Normalize();
float zRotation = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
Vector3 lookDirection = new Vector3(0, 0, zRotation - 90);
transform.rotation = Quaternion.Euler(lookDirection);
}
Given this state, the player behaves as expected, but the enemy always rotates away from the player, meaning that he looks up instead of down at where the player is.
If I switched the diff vector like this:
Vector3 diff = transform.position - target.position;
Then it's the player that looks away from the enemy.
Both sprites have 0 values for rotation and scale in the editor.
What is wrong here?
Your solution works fine for me: http://imgur.com/a/spi3O
Could it be that the "up" for the Enemy is the "down" for the player. Meaning one of your sprites is drawn upside down?
You can try the following, but it yields the same result:
var dir = target.position - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
If you're going to use the same method of calculating the rotation, you need to assure that your sprites have the same world-relative native rotation, or fix that.

Unity3d - How to walk throught streets

I have a 3d city model. I want to walk throught walls/steets. There are some advices for this.
Ex1, ex2, ex3
Generally, they said that you should add a collider to your model. I did it. But I don't know next step. Should I move my camera or player gameobject? Should I handle click movement key in code?
I attach below code to my camera. It works for me. I take this code from this tutorial.
public float speed = 10.0f;
public float rotationSpeed = 100.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float translation = Input.GetAxis ("Vertical") * speed;
float rotation = Input.GetAxis ("Horizontal") * rotationSpeed;
translation *= Time.deltaTime;
rotation *= Time.deltaTime;
transform.Translate (0, 0, translation);
transform.Rotate (0, rotation, 0);
}