I am having an application in which I have to increase android brightness using the swipe up and down but the issue is I want to increase the brightness continuously If I scroll up and decrease also if I scroll down. My code is
if(t.phase == TouchPhase.Ended)
{
//save ended touch 2d point
secondPressPos = new Vector2(t.position.x,t.position.y);
//create vector from the two points
currentSwipe = new Vector3(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
//normalize the 2d vector
currentSwipe.Normalize();
//swipe upwards
if(currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f)
{
if(Brightness >= 1.0f)
{
Brightness = 1.0f;
}
else if (Brightness <= -1.0f){
Brightness = 0.0f;
}
else{
Brightness = Brightness + 0.2f;
}
}
}
This code works only If I want to increase or decrease the brightness by some value but then I have to swipe again which I don't want.
I would simply not normalize the vector but rather use it as a factor like e.g.
// Configure some threshold (in pixels) the user has to swipe before changing the brightness
[SerializeField] private float THRESHOLD = 0f;
// Since the position change is in pixels of the display
// configure here how this movement is mapped into your brightness change
[SerializeField] private float SENSITIVITY = 0.01f;
private void Update()
{
if(Input.touchCount < 1) return;
var t = Input.GetTouch(0);
switch (t.phase)
{
case TouchPhase.Began:
firstPressPos = t.position;
break;
case TouchPhase.Moved:
secondPressPos = t.position;
var currentSwipe = secondPressPos - firstPressPos;
if(Mathf.Abs(currentSwipe.x) < 0.5f && Mathf.Abs(currentSwipe.y) > THRESHOLD)
{
// remove the threshold amount
currentSwipe.y -= Mathf.Sign(currentSwipe.y) * THRESHOLD;
// Smooth change the brightness instead of stepwise
// depending on how far the user swiped
Brightness += currentSwipe.y * SENSITIVITY;
// Sanatize value between 0 and 1
Brightness = Mathf.Clamp(Brightness, 0, 1);
}
break;
}
}
Related
LocationBasedGame sample in Unity is used to create a location acquisition application.
I want to be able to zoom in and out with a pinch-in/out motion since I am using it on a smartphone.
With that in mind, I have created the following script.
I actually built it on a smartphone and checked the console and it appears to work as expected.
However, it does not zoom in on the map.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using Mapbox.Unity.Map;
public class pinchout : MonoBehaviour
{
public AbstractMap map;
float dist0 = 0f;
float dist1 = 0f;
float scale = 0f;
float oldDist = 0f;
float minRate = 0.7f;
float maxRate = 3f;
Vector3 v = Vector3.zero;
void Start()
{
}
void Update()
{
//Pinch-in/out decision process until the next comment
if (Input.touchCount >= 2)
{
Touch t1 = Input.GetTouch(0);
Touch t2 = Input.GetTouch(1);
if (t2.phase == TouchPhase.Began)
{
dist0 = Vector2.Distance(t1.position, t2.position);
oldDist = dist0;
}
else if (t1.phase == TouchPhase.Moved && t2.phase == TouchPhase.Moved)
{
dist1 = Vector2.Distance(t1.position, t2.position);
if (dist0 < 0.001f || dist1 < 0.001f)
{
return;
}
else
{
v = transform.localScale;
scale = v.x;
scale += (dist1 - oldDist) / 100000f;
if (scale > maxRate) { scale = maxRate; }
if (scale < minRate) { scale = minRate; }
oldDist = dist1;
}
//It takes the default zoom value and adds the value obtained by pinching in and out to it.
float zoom_count;
zoom_count = map.Options.locationOptions.zoom;
scale = scale / 50;
//The max value is 22, so I'm processing it by determining if it is less than 22 or not.
if (scale > 0.02)
{
scale = scale + zoom_count;
if (scale < 22)
{
map.Options.locationOptions.zoom = scale;
} else
{
scale = 22;
map.Options.locationOptions.zoom = scale;
}
Debug.Log(scale);
}
else
{
scale = zoom_count - scale;
if(0.02 > scale)
{
scale = 1;
map.Options.locationOptions.zoom = scale;
}
else
{
map.Options.locationOptions.zoom = scale;
}
Debug.Log(scale);
}
}
}
}
}
I am a beginner in unity So, I wanted to Make A Fortune Wheel But Instead of Rotating it with a button I want Like, the speed of its spinning will depend on how fast I touch n' dragged the wheel itself.
If I flick/rotate it very fast, the wheel would go spinning faster.
If I only moved it slowly, then it would barely spin at all. Just like what would happen if you spin a wheel like in Wheel of Fortune in real life.
Thanks
Touch control object rotation and zoom in Unity.
using UnityEngine;
using System.Collections;
using System.IO;
public class ScaleAndRotate : MonoBehaviour
{
private Touch oldTouch1; //Last touch point 1 (finger 1)
private Touch oldTouch2; //Last touch point 2 (finger 2)
void Start()
{
}
void Update() {
// no touch
if ( Input. touchCount <= 0 ){
return;
}
//Single touch, rotate horizontally up and down
if( 1 == Input.touchCount ){
Touch touch = Input.GetTouch(0);
Vector2 deltaPos = touch.deltaPosition;
transform.Rotate(Vector3.down * deltaPos.x , Space.World);
transform.Rotate(Vector3.right * deltaPos.y , Space.World);
}
//Multi-touch, zoom in and out
Touch newTouch1 = Input.GetTouch(0);
Touch newTouch2 = Input.GetTouch(1);
//The second point just started touching the screen, only recording, not processing
if( newTouch2.phase == TouchPhase.Began ){
oldTouch2 = newTouch2;
oldTouch1 = newTouch1;
return;
}
//Calculate the distance between the old two points and the distance between the new two points. When it becomes larger, you need to enlarge the model, and when it becomes smaller, you need to zoom the model.
float oldDistance = Vector2.Distance(oldTouch1.position, oldTouch2.position);
float newDistance = Vector2.Distance(newTouch1.position, newTouch2.position);
//The difference between the two distances, positive means zoom in gesture, negative means zoom out gesture
float offset = newDistance - oldDistance;
//Amplification factor, one pixel is calculated by 0.01 times (100 can be adjusted)
float scaleFactor = offset / 100f;
Vector3 localScale = transform.localScale;
Vector3 scale = new Vector3(localScale.x + scaleFactor,
localScale.y + scaleFactor,
localScale.z + scaleFactor);
//Minimum zoom to 0.3 times
if (scale.x > 0.3f && scale.y > 0.3f && scale.z > 0.3f) {
transform.localScale = scale;
}
//Remember the latest touch point and use it next time
oldTouch1 = newTouch1;
oldTouch2 = newTouch2;
}
}
Hope it helps you.
I created a level menu manager where you swipe from one screen to the next horizontally, and it worked great. Until I realized I had to change the canvas to scale with screen size in order to preserve the layout for various devices. Now, the panels resize. Which is what I want, however it means the swipe no longer works since the panels stretch and thin to accommodate yet their position does not change. They might overlap now, or have big gaps in between. See photo examples. Is there anything I can do? I cannot for the life of me figure out how to calculate where their new position should be based on screen size and move them there using the left and right rect transform properties. It sounds easy but the math just does not math in all my efforts. Been tearing my hair out over this all day.
Code for my page swiper:
public class PageSwiper : MonoBehaviour, IDragHandler, IEndDragHandler
{
private Vector3 panelLocation;
public float percentThreshold = 0.2f;
public float easing = 0.5f;
int currentChild;
Player player;
void Start()
{
player = PlayerData.GetPlayerData();
currentChild = player.lastPanel;
panelLocation = transform.position;
panelLocation += new Vector3(-Screen.width * (currentChild-1), 0, 0);
transform.position = panelLocation;
}
public void OnDrag(PointerEventData data){
float difference = data.pressPosition.x - data.position.x;
if ((currentChild == 9 && difference < 0) || (currentChild == 1 && difference > 0))
{
transform.position = panelLocation - new Vector3(difference, 0, 0);
}
}
public void OnEndDrag(PointerEventData data){
float percentage = (data.pressPosition.x - data.position.x) / Screen.width;
if (Mathf.Abs(percentage) >= percentThreshold){
Vector3 newLocation = panelLocation;
int panelCount = transform.childCount - 1;
if (percentage > 0 && currentChild < panelCount){
newLocation += new Vector3(-Screen.width, 0, 0);
currentChild += 1;
}else if(percentage < 0 && currentChild > 1){
newLocation += new Vector3(Screen.width, 0, 0);
currentChild -= 1;
}
transform.position = newLocation;
panelLocation = newLocation;
} else {
transform.position = panelLocation;
}
}
}
Before, right next to each other for perfect swipe:
After example 1, wider screen size:
After example 2, thinner screen size:
I'm trying to implement a system where my camera will zoom in on the front face of a gameobject and I can then rotate around it with clamping.
I've managed to get it work, though I'm guessing I've done it totally wrong - Basically I'm expecting actualAngle to be NEGATIVE when I pan to the left and POSITIVE when I pan to the right.
It does work for targets that have no rotation but not for targets that do have a rotation as the centred angle is not zero.
Here's my function:
float _prevMousePosX;
void RotateCamera()
{
//Allow min -30 degrees when panning to the left
minXLimit = -50;
//And max 30 degrees when panning to the right
maxXLimit = 50;
//Work out how much the mouse has moved
var mouseX = Input.GetAxis("Mouse X");
Vector3 angle = target.position + target.rotation * transform.position * -1;
var actualAngle = angle.x;
//The angle is very small so times it by 100
actualAngle = actualAngle * 100;
//This angle is not defaulting to zero before any rotation has occurred when the game object has a rotation other than zero - I think I should be taking into account the existing rotation somehow
Debug.Log(actualAngle);
//The rest of this code is working correctly
if ((actualAngle > minXLimit && actualAngle < maxXLimit && isMoving))
{
//No - Allow rotating in either direction horizontally
if(isMoving) transform.RotateAround(target.transform.position, Vector3.up, mouseX * 1);
} else
{
//Yes, it's more than 30 degrees either left or right
//Work out which way wer're trying to drag the mouse and whether we should allow rotation further in that direction
if (mouseX>0 && actualAngle < minXLimit)
{
//Don't allow?
}
else if (mouseX<0 && actualAngle < minXLimit)
{
//Allow rotating back
if (isMoving) transform.RotateAround(target.transform.position, Vector3.up, mouseX * 1);
}
else
{
//Mouse isn't moving
}
if (mouseX>0 && actualAngle > maxXLimit)
{
//Allow rotating back
if (isMoving) transform.RotateAround(target.transform.position, Vector3.up, mouseX * 1);
}
else if(mouseX<0 && actualAngle > maxXLimit)
{
//Don't allow rotating in this direction any further
} else
{
//Mouse isn't moving
}
}
_prevMousePosX = mouseX;
}
Issue resolved.
//Work out how close we are to facing each other
//We can minus 180 because we'll always be facing each other, but just not always directly
var newAngle = Quaternion.Angle(target.rotation, transform.rotation) -180;
//Then we need to work out whether we are to it's left or it's right
float rotateDirection = (((transform.eulerAngles.y - target.eulerAngles.y) + 360f) % 360f) > 180.0f ? 1 : -1;
var actualAngle = newAngle;
//And finally we can negate our degrees if we're to it's left
actualAngle = actualAngle * rotateDirection;
You can then use actualAngle to clamp your rotation as I do above.
I have an orthographic camera and would like to implement a zoom feature to a specific point. I.e., imagine you have a picture and want to zoom to a specific part of the picture.
I know how to zoom in, the problem is to move the camera to a position that has the desired zone in focus.
How can I do so?
The camera's orthographicSize is the number of world space units in the top half of the viewport. If it's 0.5, then a 1 unit cube will exactly fill the viewport (vertically).
So to zoom in on your target region, center your camera on it (by setting (x,y) to the target's center) and set orthographicSize to half the region's height.
Here is an example to center and zoom to the extents of an object. (Zoom with LMB; 'R' to reset.)
public class OrthographicZoom : MonoBehaviour
{
private Vector3 defaultCenter;
private float defaultHeight; // height of orthographic viewport in world units
private void Start()
{
defaultCenter = camera.transform.position;
defaultHeight = 2f*camera.orthographicSize;
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Collider target = GetTarget();
if(target != null)
OrthoZoom(target.bounds.center, target.bounds.size.y); // Could directly set orthographicSize = bounds.extents.y
}
if (Input.GetKeyDown(KeyCode.R))
OrthoZoom(defaultCenter, defaultHeight);
}
private void OrthoZoom(Vector2 center, float regionHeight)
{
camera.transform.position = new Vector3(center.x, center.y, defaultCenter.z);
camera.orthographicSize = regionHeight/2f;
}
private Collider GetTarget()
{
var hit = new RaycastHit();
Physics.Raycast(camera.ScreenPointToRay(Input.mousePosition), out hit);
return hit.collider;
}
}
hope you find this code example useful, should be a copy / paste.
Note: this script assume it's attached to the camera object, otherwise you should adjust the transform to the camera object reference.
private float lastZoomDistance = float.PositiveInfinity; // remember that this should be reset to infinite on touch end
private float maxZoomOut = 200;
private float maxZoomIn = 50;
private float zoomSpeed = 2;
void Update() {
if (Input.touchCount >= 2) {
Vector2 touch0, touch1;
float distance;
Vector2 pos = new Vector2(transform.position.x, transform.position.y);
touch0 = Input.GetTouch(0).position - pos;
touch1 = Input.GetTouch(1).position - pos;
zoomCenter = (touch0 + touch1) / 2;
distance = Vector2.Distance(touch0, touch1);
if(lastZoomDistance == float.PositiveInfinity) {
lastZoomDistance = distance;
} else {
if(distance > lastZoomDistance && camera.orthographicSize + zoomSpeed <= maxZoomOut) {
this.camera.orthographicSize = this.camera.orthographicSize + zoomSpeed;
// Assuming script is attached to camera - otherwise, change the transform.position to the camera object
transform.position = Vector3.Lerp(transform.position, zoomCenter, Time.deltaTime);
} else if(distance < lastZoomDistance && camera.orthographicSize - zoomSpeed >= maxZoomIn) {
this.camera.orthographicSize = this.camera.orthographicSize - zoomSpeed;
transform.position = Vector3.Lerp(transform.position, zoomCenter, Time.deltaTime);
}
}
lastZoomDistance = distance;
}
}