camera preview showing blank screen - android-camera

public class cameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
private Activity act;
private int currentCameraId;
private boolean cameraFront;
private boolean InPreview;
//private SurfaceView SV;
public cameraPreview(Context context, Activity A, SurfaceView SFV) {
super(context);
mCamera = null;
mHolder = null;
InPreview = false;
act = A;
mHolder = SFV.getHolder();
mHolder.addCallback(this);
initialzeCamera();
}
private void initialzeCamera()
{
initializeCameraBool();
OpenCamera();
}
public void OpenCamera()
{
if(mCamera==null)
{
Log.e("open", "sesami");
if(cameraFront)
mCamera.open(cameraPreview.findFrontFacingCamera());
else
mCamera.open(cameraPreview.findBackFacingCamera());
}
//StartPreview();
}
private void StartPreview()
{
if (mHolder.getSurface() == null || mCamera == null){
Log.e("Stop", "in the name of the law");
return;
}
Log.e("Started", "from the bottom");
if(InPreview)
{
mCamera.stopPreview();
InPreview = false;
}
setCameraDisplayOrientation();
if(!InPreview)
{
try {
mCamera.setPreviewDisplay(mHolder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();
InPreview = true;
}
}
public void releaseCamera()
{
if (mCamera != null) {
if(InPreview)
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
public void surfaceCreated(SurfaceHolder holder) {
StartPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
releaseCamera();
}
public void setCameraDisplayOrientation() {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(currentCameraId, info);
int rotation = act.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
if(mCamera!=null)
mCamera.setDisplayOrientation(result);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
StartPreview();
}
public static int findBackFacingCamera() {
int cameraId = -1;
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
break;
}
}
return cameraId;
}
public static int findFrontFacingCamera() {
int cameraId = -1;
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
break;
}
}
return cameraId;
}
private void initializeCameraBool()
{
if(cameraPreview.findBackFacingCamera()>=0)
cameraFront = false;
else
cameraFront = true;
}
}
So the surfaceview that I pass in comes from the main activity and it's getting it from the layout. The layout is just a surfaceview. When I launch it though it only shows a black screen. I don't understand why this is happening. It should be launching the preview display but for some reason it doesn't show it.

Related

Unity-Help needed to turn my keyboard and mouse inputs to setup mobile input

Hey so I have this input script working fine for the PC just wanted to try mobile input. Can someone help to turn this script to work with mobile? I haven't tried anything yet first time trying mobile input. Just tell me how to set up this script with mobile and UI components.
QWERTYUIOPASDFGHJKLZXCVBNM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInput : MonoBehaviour
{
public Vector2 input
{
get
{
Vector2 i = Vector2.zero;
i.x = Input.GetAxis("Horizontal");
i.y = Input.GetAxis("Vertical");
i *= (i.x != 0.0f && i.y != 0.0f) ? .7071f : 1.0f;
return i;
}
}
public Vector2 down
{
get { return _down; }
}
public Vector2 raw
{
get
{
Vector2 i = Vector2.zero;
i.x = Input.GetAxisRaw("Horizontal");
i.y = Input.GetAxisRaw("Vertical");
i *= (i.x != 0.0f && i.y != 0.0f) ? .7071f : 1.0f;
return i;
}
}
public float elevate
{
get
{
return Input.GetAxis("Elevate");
}
}
public bool run
{
get { return Input.GetKey(KeyCode.LeftShift); }
}
public bool crouch
{
get { return Input.GetKeyDown(KeyCode.C); }
}
public bool crouching
{
get { return Input.GetKey(KeyCode.C); }
}
public KeyCode interactKey
{
get { return KeyCode.E; }
}
public bool interact
{
get { return Input.GetKeyDown(interactKey); }
}
public bool reload
{
get { return Input.GetKeyDown(KeyCode.R); }
}
public bool aim
{
get { return Input.GetMouseButtonDown(1); }
}
public bool aiming
{
get { return Input.GetMouseButton(1); }
}
public bool shooting
{
get { return Input.GetMouseButton(0); }
}
public float mouseScroll
{
get { return Input.GetAxisRaw("Mouse ScrollWheel"); }
}
private Vector2 previous;
private Vector2 _down;
private int jumpTimer;
private bool jump;
void Start()
{
jumpTimer = -1;
}
void Update()
{
_down = Vector2.zero;
if (raw.x != previous.x)
{
previous.x = raw.x;
if (previous.x != 0)
_down.x = previous.x;
}
if (raw.y != previous.y)
{
previous.y = raw.y;
if (previous.y != 0)
_down.y = previous.y;
}
}
public void FixedUpdate()
{
if (!Input.GetKey(KeyCode.Space))
{
jump = false;
jumpTimer++;
}
else if (jumpTimer > 0)
jump = true;
}
public bool Jump()
{
return jump;
}
public void ResetJump()
{
jumpTimer = -1;
}
}
You can use the new input system in Unity (I see that you're using an old one). It's a pretty convenient way to make sure that your input are generalizable for a wide range of input controllers.
https://www.youtube.com/watch?v=Yjee_e4fICc

OverlapBoxAll 2d dont detect anything

This script should detect the collision with the colliders of the Hurtbox layer (using OverlapBoxAll)but it does not work I have the matrix layer configured well and the variables assigned in the inspector so I do not know what my error is.
pd: The collision ocurs in HitboxUpdate method
My collision layer matrix 2d:
https://answers.unity.com/storage/temp/173342-sin-titulo.png
The scene and hierarchy:
https://answers.unity.com/storage/temp/173344-scene.png
The script:
public string owner = "-1";
public Vector3 boxSize;
public Vector3 position;
public Quaternion rotation;
public LayerMask mask;
public bool useSphere = false;
public float radius = 0.5f;
public Color inactiveColor;
public Color collisionOpenColor;
public Color collidingColor;
private ColliderState _state;
// ignoreList = ds_List_create()
public float hitStun = 60;
private IHitboxResponder _responder = null;
// Update is called once per frame
void Update()
{
HitboxUpdate();
}
public void StartCheckingCollision()
{
_state = ColliderState.Open;
}
public void StopCheckingCollision()
{
_state = ColliderState.Closed;
}
void OnDrawGizmos()
{
// Draw a yellow sphere at the transform's position
Debug.Log("draw hitbox gizmos");
CheckGizmoColor();
Gizmos.matrix = Matrix4x4.TRS(transform.position, transform.rotation, transform.localScale);
if (useSphere)
{
Gizmos.DrawSphere(Vector3.zero, radius); }
else
{
Gizmos.DrawCube(position, new Vector3(boxSize.x * 2, boxSize.y * 2, boxSize.z * 2));
}
}
private void CheckGizmoColor()
{
switch (_state)
{
case ColliderState.Closed:
Gizmos.color = inactiveColor;
Debug.Log("Closed");
break;
case ColliderState.Open:
Gizmos.color = collisionOpenColor;
Debug.Log("Open");
break;
case ColliderState.Colliding:
Gizmos.color = collidingColor;
Debug.Log("colliding");
break;
}
}
public void HitboxUpdate()
{
StartCheckingCollision();
if (_state == ColliderState.Closed)
{
Debug.Log("Collider cloded");
return;
}
Debug.Log("Collider open hit");
Collider2D[] colliders = Physics2D.OverlapBoxAll(position, boxSize, transform.eulerAngles.z ,mask);
if (colliders.Length > 0)
{
_state = ColliderState.Colliding;
Debug.Log("We hit something hitbox");
}
if (colliders.Length > 0)
{
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject.GetComponent<Hurtbox>() != null)
{
if (colliders[i].gameObject.GetComponent<Hurtbox>().owner == owner)
{
Debug.Log("collider skiped");
colliders = colliders.Skip(i).ToArray();
}
}
Debug.Log("Hit " + colliders[i].gameObject.name);
}
}
for (int i = 0; i < colliders.Length; i++)
{
Collider2D aCollider = colliders[i];
Debug.Log("Works");
_responder?.CollisionedWith(aCollider);
}
_state = colliders.Length > 0 ? ColliderState.Colliding : ColliderState.Open;
}
public void UseResponder(IHitboxResponder responder)
{
_responder = responder;
}
}
public enum ColliderState
{
Closed,
Open,
Colliding
}
Change
Collider2D[] colliders = Physics2D.OverlapBoxAll(position, boxSize, transform.eulerAngles.z ,mask);
to
Collider2D[] colliders = Physics2D.OverlapBoxAll(position, boxSize ,mask);

Player want to move left and right from single - touch (Unity)

I made the game in Unity Space Shooter. In my Space shooter there is 2 button it work for Left and Right moving. I want when we touch the left button player go to left only in Single Touch same like Right Button also.
This , are the some codes which i used in Game. Please Help me out from this.
TouchControl.cs
using UnityEngine;
using System.Collections;
public class TouchControl : MonoBehaviour {
public GUITexture moveLeft;
public GUITexture moveRight;
public GUITexture fire;
public GameObject player;
private PlayerMovement playerMove;
private Weapon[] weapons;
void Start()
{
playerMove = player.GetComponent<PlayerMovement> ();
}
void CallFire()
{
weapons = player.GetComponentsInChildren<Weapon> ();
foreach (Weapon weapon in weapons) {
if(weapon.enabled == true)
weapon.Fire();
}
}
void Update()
{
// int i = 0;
if(Input.touchCount > 0)
{
for(int i =0; i < Input.touchCount; i++)
{
// if(moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
// {
// if(Input.touchCount > 0)
// {
// playerMove.MoveLeft();
// }
// }
// if(moveRight.HitTest(Input.GetTouch(i).position, Camera.main))
// {
// if(Input.touchCount > 0)
// {
// playerMove.MoveRight();
// }
// }
// if(moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
// {
// if(Input.touchCount > 0)
// {
// CallFire();
// }
// }
// Touch t = Input.GetTouch(i);
Touch t = Input.GetTouch (i);
Input.multiTouchEnabled = true;
if(t.phase == TouchPhase.Began || t.phase == TouchPhase.Stationary)
{
if(moveLeft.HitTest(t.position, Camera.main))
{
playerMove.MoveLeft ();
}
if(moveRight.HitTest(t.position, Camera.main))
{
playerMove.MoveRight();
}
}
if(t.phase == TouchPhase.Began)
{
if(fire.HitTest(t.position, Camera.main))
{
CallFire();
}
}
if(t.phase == TouchPhase.Ended)
{
}
}
}
}
}
PlayerMovement.cs
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public float speedMove = 6.0f;
public float bonusTime;
private bool toLeft = false;
private bool toRight = false;
public GameObject shield;
public GUIText bonustimeText;
private bool counting = false;
private float counter;
private Weapon[] addWeapons;
public Sprite strongShip;
public Sprite normalSprite;
public Sprite shieldSprite;
private SpriteRenderer sRender;
private Weapon weaponScript;
void Start () {
counter = bonusTime;
sRender = GetComponent<SpriteRenderer> ();
addWeapons = GetComponentsInChildren<Weapon> ();
foreach (Weapon addWeapon in addWeapons) {
addWeapon.enabled = false;
}
weaponScript = GetComponent<Weapon>();
weaponScript.enabled = true;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.A)) {
toLeft = true;
}
if (Input.GetKeyUp (KeyCode.A)) {
toLeft = false;
}
if (Input.GetKeyDown (KeyCode.D)) {
toRight = true;
}
if (Input.GetKeyUp (KeyCode.D)) {
toRight = false;
}
if (counting) {
counter -= Time.deltaTime;
bonustimeText.text = counter.ToString("#0.0");
}
}
void FixedUpdate()
{
if (toLeft) {
MoveLeft();
}
if (toRight) {
MoveRight();
}
}
public void MoveLeft()
{
transform.Translate(Vector2.right * -speedMove* Time.deltaTime);
}
public void MoveRight()
{
transform.Translate(Vector2.right * speedMove * Time.deltaTime);
}
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "StrongMode") {
Destroy (coll.gameObject);
counting = true;
StrongMode();
Invoke ("Downgrade", bonusTime);
}
if (coll.gameObject.tag == "ShieldMode") {
Destroy (coll.gameObject);
counting = true;
ShieldMode();
Invoke("Downgrade", bonusTime);
}
if (coll.gameObject.tag == "Life") {
GUIHealth gui = GameObject.Find ("GUI").GetComponent<GUIHealth> ();
gui.AddHealth();
SendMessage("AddHp");
SoundHelper.instanceSound.PickUpSound();
Destroy(coll.gameObject);
}
if (coll.gameObject.tag == "Enemy") {
SendMessage("Dead");
}
}
void Downgrade()
{
SoundHelper.instanceSound.BonusDownSound ();
counting = false;
bonustimeText.text = "";
counter = bonusTime;
sRender.sprite = normalSprite;
weaponScript.enabled = true;
foreach (Weapon addWeapon in addWeapons) {
addWeapon.enabled = false;
}
weaponScript.enabled = true;
shield.SetActive (false);
}
void StrongMode()
{
SoundHelper.instanceSound.BonusUpSound ();
sRender.sprite = strongShip;
foreach (Weapon addWeapon in addWeapons) {
addWeapon.enabled = true;
}
weaponScript.enabled = false;
}
void ShieldMode()
{
SoundHelper.instanceSound.BonusUpSound ();
sRender.sprite = shieldSprite;
shield.SetActive (true);
}
// void OnDestroy()
// {
// bonustimeText.text = "";
// }
}
In the Player Controller script Create:
public Vector3 playerDirection = Vector3.zero;
Then in touch control instead of:
if (moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.MoveLeft();
}
}
if (moveRight.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.MoveRight();
}
}
Use:
if (moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.playerDirection = Vector3.left;
}
}
if (moveRight.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.playerDirection = Vector3.right;
}
}
Then in the Update method of Player Controller use:
transform.Translate(playerDirection * speedMove * Time.deltaTime);
public class PlayerController {
public EPlayerState playerState = EPLayerState.Idle;
void Update () {
// If click right button
playerState = EPlayerState.MoveRight;
// Else if click left button
playerState = EPlayerState.MoveLeft
if (playerState == EPlayerState.MoveRight)
// Move player right;
if (playerState == EPlayerState.MoveLeft
// Move player right;
}
}
public enum EPlayerState {
Idle,
MoveRight,
MoveLeft
}
You can also use something like a boolean called isRight, move right when it's true and left when it's false. Then when you click left or right button just change the variable.
`using UnityEngine;
public class HalfScreenTouchMovement : MonoBehaviour
{
private float screenCenterX;
private void Start()
{
// save the horizontal center of the screen
screenCenterX = Screen.width * 0.5f;
}
private void Update()
{
// if there are any touches currently
if(Input.touchCount > 0)
{
// get the first one
Touch firstTouch = Input.GetTouch(0);
// if it began this frame
if(firstTouch.phase == TouchPhase.Began)
{
if(firstTouch.position.x > screenCenterX)
{
// if the touch position is to the right of center
// move right
}
else if(firstTouch.position.x < screenCenterX)
{
// if the touch position is to the left of center
// move left
}
}
}
}
}`
May be helpfull
create script. for example player.cs
public class PlayerController : MonoBehaviour
{
bool swipeRight = false;
bool swipeLeft = false;
bool touchBlock = true;
bool canTouchRight = true;
bool canTouchLeft = true;
void Update()
{
swipeLeft = Input.GetKeyDown("a") || Input.GetKeyDown(KeyCode.LeftArrow);
swipeRight = Input.GetKeyDown("d") || Input.GetKeyDown(KeyCode.RightArrow);
TouchControl();
if(swipeRight) //rightMove logic
else if(swipeLeft) //leftMove logic
}
void TouchControl()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved && touchBlock == true)
{
touchBlock = false;
// Get movement of the finger since last frame
var touchDeltaPosition = Input.GetTouch(0).deltaPosition;
Debug.Log("touchDeltaPosition "+touchDeltaPosition);
if(touchDeltaPosition.x > 0 && canTouchRight == true)
{
//rightMove
swipeRight = true; canTouchRight = false;
Invoke("DisableSwipeRight",0.2f);
}
else if(touchDeltaPosition.x < 0 && canTouchLeft == true)
{
//leftMove
swipeLeft = true; canTouchLeft = false;
Invoke("DisableSwipeLeft",0.2f);
}
}
}
void DisableSwipeLeft()
{
swipeLeft = false;
touchBlock = true;
canTouchLeft = true;
}
void DisableSwipeRight()
{
swipeRight = false;
touchBlock = true;
canTouchRight = true;
}
}

How to program custom buttons to navigate through scroll view created with Scroll Rect combined with a Mask

I have a shop GUI, its content in a srollview created with Scroll Rect and Mask combination and can be scrolled down and up.
Right now, the scroll view scrolls by clicking and dragging with the mouse anywhere in scroll view area, or by interacting with a vertical scrollbar.
How do I use custom up and down buttons (circled in red on attached image below) to make the scroll happen?
Copy the following script to your project and apply ScrollRectSnap script to your scroll view . Know if you have done this to make your scroll view snap on button click simply do the following link UpArrowPressed and DownArrowPressed with your up and down buttons and do not forget to check Snap In V parameter in inspector of ScrollRectSnap if you have vertical scrollview and also do not get confused by snapper.DraggedOnRight() call in your DownArrowPressed function as if you have checked Snap In V parameter it will then act like snap down and similler thing with snapper.DraggedOnLeft() other parameters you can set according to your requirment you will have to play with values in order to get it according to your requirments.
public void UpArrowPressed()
{
ScrollRectSnap snapper = GetComponentInChildren<ScrollRectSnap>();
snapper.DraggedOnLeft();
}
public void DownArrowPressed()
{
ScrollRectSnap snapper = GetComponentInChildren<ScrollRectSnap>();
snapper.DraggedOnRight();
}
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class ScrollRectSnap : MonoBehaviour
{
float[] points;
[Tooltip("how many screens or pages are there within the content (steps)")]
public int screens = 1;
[Tooltip("How quickly the GUI snaps to each panel")]
public float snapSpeed;
public float inertiaCutoffMagnitude;
float stepSize;
ScrollRect scroll;
bool LerpH;
float targetH;
[Tooltip("Snap horizontally")]
public bool snapInH = true;
bool LerpV;
float targetV;
[Tooltip("Snap vertically")]
public bool snapInV = true;
public string controllTag;
bool dragInit = true;
int dragStartNearest;
float horizontalNormalizedPosition;
float verticalNormalizedPosition;
public static event Action<int,int> OnEndReached;
public static event Action<int,int,string> OnEndReachedWithTag;
// Use this for initialization
void Start()
{
Init();
// SnapToSelectedIndex(0);
}
void Init()
{
scroll = gameObject.GetComponent<ScrollRect>();
scroll.inertia = true;
if (screens > 0)
{
points = new float[screens];
stepSize = (float)Math.Round(1 / (float)(screens - 1),2);
for (int i = 0; i < screens; i++)
{
points[i] = i * stepSize;
}
}
else
{
points[0] = 0;
}
}
void OnEnable()
{
}
void Update()
{
horizontalNormalizedPosition = scroll.horizontalNormalizedPosition;
verticalNormalizedPosition = scroll.verticalNormalizedPosition;
if (LerpH)
{
scroll.horizontalNormalizedPosition = Mathf.Lerp(scroll.horizontalNormalizedPosition, targetH, snapSpeed * Time.deltaTime);
if (Mathf.Approximately((float)Math.Round(scroll.horizontalNormalizedPosition,2), targetH))
{
LerpH = false;
int target = FindNearest(scroll.horizontalNormalizedPosition, points);
// Debug.LogError("Target : " + target);
if (target == points.Length-1)
{
if (OnEndReached != null)
{
OnEndReached(1,target);
}
if(OnEndReachedWithTag != null)
{
OnEndReachedWithTag(1,target,controllTag);
}
}
else if (target == 0)
{
if (OnEndReached != null)
{
OnEndReached(-1,target);
}
if(OnEndReachedWithTag != null)
{
OnEndReachedWithTag(-1,target,controllTag);
}
}
else
{
if (OnEndReached != null)
{
OnEndReached(0,target);
}
if(OnEndReachedWithTag != null)
{
OnEndReachedWithTag(0,target,controllTag);
}
}
}
}
if (LerpV)
{
scroll.verticalNormalizedPosition = Mathf.Lerp(scroll.verticalNormalizedPosition, targetV, snapSpeed * Time.deltaTime);
if (Mathf.Approximately(scroll.verticalNormalizedPosition, targetV))
{
LerpV = false;
}
}
}
public void DragEnd()
{
int target = FindNearest(scroll.horizontalNormalizedPosition, points);
if (target == dragStartNearest && scroll.velocity.sqrMagnitude > inertiaCutoffMagnitude * inertiaCutoffMagnitude)
{
if (scroll.velocity.x < 0)
{
target = dragStartNearest + 1;
}
else if (scroll.velocity.x > 1)
{
target = dragStartNearest - 1;
}
target = Mathf.Clamp(target, 0, points.Length - 1);
}
if (scroll.horizontal && snapInH )
{
targetH = points[target];
LerpH = true;
}
if (scroll.vertical && snapInV && scroll.verticalNormalizedPosition > 0f && scroll.verticalNormalizedPosition < 1f)
{
targetH = points[target];
LerpH = true;
}
dragInit = true;
}
public void OnDrag()
{
if (dragInit)
{
if (scroll == null)
{
scroll = gameObject.GetComponent<ScrollRect>();
}
dragStartNearest = FindNearest(scroll.horizontalNormalizedPosition, points);
dragInit = false;
}
LerpH = false;
LerpV = false;
}
int FindNearest(float f, float[] array)
{
float distance = Mathf.Infinity;
int output = 0;
for (int index = 0; index < array.Length; index++)
{
if (Mathf.Abs(array[index] - f) < distance)
{
distance = Mathf.Abs(array[index] - f);
output = index;
}
}
return output;
}
public void DraggedOnLeft()
{
OnDrag();
if (scroll.horizontal && snapInH && scroll.horizontalNormalizedPosition > -0.001f && scroll.horizontalNormalizedPosition < 1.001f)
{
// Debug.Log("Before Press, LerpH : " + LerpH);
if (dragStartNearest < points.Length-1)
{
targetH = points[dragStartNearest+1];
LerpH = true;
}
else
{
targetH = points[dragStartNearest];
LerpH = true;
}
// Debug.Log("After Press, LerpH : " + LerpH);
}
if (scroll.vertical && snapInV && scroll.verticalNormalizedPosition > 0f && scroll.verticalNormalizedPosition < 1f)
{
if (dragStartNearest < points.Length-1)
{
targetV = points[dragStartNearest+1];
LerpV = true;
}
else
{
targetV = points[dragStartNearest];
LerpV = true;
}
}
dragInit = true;
}
public void DraggedOnRight()
{
OnDrag();
if (scroll.horizontal && snapInH && scroll.horizontalNormalizedPosition > -0.001f && scroll.horizontalNormalizedPosition < 1.001f)
{
if (dragStartNearest>0)
{
targetH = points[dragStartNearest-1];
LerpH = true;
}
else
{
targetH = points[dragStartNearest];
LerpH = true;
}
}
if (scroll.vertical && snapInV && scroll.verticalNormalizedPosition > 0f && scroll.verticalNormalizedPosition < 1f)
{
if (dragStartNearest > 0)
{
targetV = points[dragStartNearest-1];
LerpV = true;
}
else
{
targetV = points[dragStartNearest];
LerpV = true;
}
}
dragInit = true;
}
public void SnapToSelectedIndex(int index)
{
if (points == null)
{
Init();
}
dragInit = false;
LerpH = false;
LerpV = false;
targetH = points[index];
LerpH = true;
dragInit = true;
}
}

Unity 2D draggable movement control

I want to add a draggable-movement control thing (attached image) like Fifa mobile game in my 2D app.
I searched a lot for the idea or a basic tutorial or relevant Unity asset. But didn't find one.
Help me with an example or URL.
You can use this if you would like, it works on web and mobile
using UnityEngine;
using System.Collections;
public class JoyStick : MonoBehaviour {
public Texture areaTexture;
public Texture touchTexture;
public Vector2 joystickPosition = new Vector2( 50f,50f);
public Vector2 speed = new Vector2(2,100);
public float zoneRadius=100f;
public float touchSize = 30;
public float deadZone=20;
public float touchSizeCoef=0;
protected Vector2 joystickAxis;
protected Vector2 joystickValue;
public Vector2 joyTouch;
private Vector2 _joystickCenter;
[SerializeField]
private Vector2 _smoothing = new Vector2(20f,20f);
public Vector2 Smoothing
{
get {
return this._smoothing;
}
set {
_smoothing = value;
if (_smoothing.x<0.1f){
_smoothing.x=0.1f;
}
if (_smoothing.y<0.1){
_smoothing.y=0.1f;
}
}
}
private int _joystickIndex=-1;
private bool _enaReset;
private bool _enaZoom;
void Start ()
{
zoneRadius = Screen.width*0.07f;
touchSize = Screen.width*0.07f;
joystickPosition = new Vector2(Screen.width*0.12f,Screen.width*0.12f);
_joystickCenter = joystickPosition;
_enaReset=false;
}
void Update ()
{
if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android)
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
{
if (_joystickIndex==touch.fingerId){
_joystickIndex=-1;
_enaReset=true;
}
}
if(_joystickIndex==touch.fingerId)
{
OnTouchDown(touch.position);
}
if (touch.phase == TouchPhase.Began)
{
if (((Vector2)touch.position - _joystickCenter).sqrMagnitude < Mathf.Pow((zoneRadius+touchSizeCoef/2),2))
{
_joystickIndex = touch.fingerId;
}
}
}
UpdateJoystick();
if(_enaReset)
{
ResetJoystick();
}
}
else
{
if (Input.GetButtonUp ("Fire1"))
{
_joystickIndex=-1;
_enaReset=true;
}
if(_joystickIndex==1)
{
OnTouchDown(Input.mousePosition);
}
if (Input.GetButtonDown ("Fire1") )
{
if (((Vector2)Input.mousePosition - _joystickCenter).sqrMagnitude <Mathf.Pow( (zoneRadius+touchSizeCoef/2),2))
{
_joystickIndex = 1;
}
}
if(_enaReset)
{
ResetJoystick();
}
UpdateJoystick();
}
}
private void UpdateJoystick()
{
if (joyTouch.sqrMagnitude>deadZone*deadZone)
{
joystickAxis = Vector2.zero;
if (Mathf.Abs(joyTouch.x)> deadZone)
{
joystickAxis = new Vector2( (joyTouch.x -(deadZone*Mathf.Sign(joyTouch.x)))/(zoneRadius-touchSizeCoef-deadZone),joystickAxis.y);
}
else
{
joystickAxis = new Vector2( joyTouch.x /(zoneRadius-touchSizeCoef),joystickAxis.y);
}
if (Mathf.Abs(joyTouch.y)> deadZone)
{
joystickAxis = new Vector2( joystickAxis.x,(joyTouch.y-(deadZone*Mathf.Sign(joyTouch.y)))/(zoneRadius-touchSizeCoef-deadZone));
}
else{
joystickAxis = new Vector2( joystickAxis.x,joyTouch.y/(zoneRadius-touchSizeCoef));
}
}
else{
joystickAxis = new Vector2(0,0);
}
Vector2 realvalue = new Vector2( speed.x*joystickAxis.x,speed.y*joystickAxis.y);
joystickValue=realvalue;
//print(realvalue);
}
void OnTouchDown(Vector2 position)
{
joyTouch = new Vector2( position.x, position.y) - _joystickCenter;
if ((joyTouch/(zoneRadius-touchSizeCoef)).sqrMagnitude > 1)
{
joyTouch.Normalize();
joyTouch *= zoneRadius-touchSizeCoef;
}
//print(joyTouch);
}
private void ResetJoystick()
{
if (joyTouch.sqrMagnitude>0.1)
{
joyTouch = new Vector2( joyTouch.x - joyTouch.x*_smoothing.x*Time.deltaTime, joyTouch.y - joyTouch.y*_smoothing.y*Time.deltaTime);
}
else{
joyTouch = Vector2.zero;
_enaReset=false;
}
}
void OnGUI()
{
GUI.DrawTexture( new Rect(_joystickCenter.x -zoneRadius ,Screen.height- _joystickCenter.y-zoneRadius,zoneRadius*2,zoneRadius*2), areaTexture,ScaleMode.ScaleToFit,true);
GUI.DrawTexture( new Rect(_joystickCenter.x+(joyTouch.x -touchSize) ,Screen.height-_joystickCenter.y-(joyTouch.y+touchSize),touchSize*2,touchSize*2), touchTexture,ScaleMode.ScaleToFit,true);
}
}