- Home /
2D Game Player Boundaries
Hello everyone! I'm making a similar game like this:
https://www.youtube.com/watch?v=N_U7GNchLZc
At minute 39 +/- it shows how to make boundaries for Input.mousePosition, but my problem is that I'm making the game for Android platform and I don't want my "Hat" to "Teleport" everytime I touch the screen I want something more like dragging finger to move player or making 2 Buttons and move left/right with Screen Boundaries and without being "Teleported" to wherever I touch.
CODE C#: using UnityEngine; using System.Collections;
public class HatController : MonoBehaviour {
public Camera cam;
private float maxWidth;
// Use this for initialization
void Start () {
if (cam == null) {
cam = Camera.main;
}
Vector3 upperCorner = new Vector3 (Screen.width, Screen.height, 0.0f);
Vector3 targetWidth = cam.ScreenToWorldPoint (upperCorner);
float hatWidth = renderer.bounds.extents.x;
maxWidth = targetWidth.x - hatWidth;
}
// Update is called once per frame
void FixedUpdate () {
Vector3 rawPosition = cam.ScreenToWorldPoint (Input.mousePosition);
Vector3 targetPosition = new Vector3 (rawPosition.x, -3.2f, 0.0f);
float targetWidth = Mathf.Clamp (targetPosition.x, -maxWidth, maxWidth);
targetPosition = new Vector3 (targetWidth, targetPosition.y, targetPosition.z);
rigidbody2D.MovePosition (targetPosition);
}
}
Your answer
Follow this Question
Related Questions
Procedural platformer: add/remove or pooling for platforms? 2 Answers
How to turn off a collider when I activate it (Basic Sword mechanic) [2D] 2 Answers
Shooting myself in multiplayer 2D platformer? 0 Answers
Character flies away after clicking play 0 Answers
Avoid enemy sprite overlapping 1 Answer