Problems with Gear VR touchpad moving the camera - c#

I can't get my Gear VR touchpad to work - I'm just trying to move the camera position on touch. I've tried both pieces of code below:
public Camera cam;
void Update()
{
if (Input.GetMouseButton (0))
{
cam.transform.position = new Vector3(-100f, -100f, -100f);
}
}
and
void Start ()
{
OVRTouchpad.Create();
OVRTouchpad.TouchHandler += HandleTouchHandler;
}
void HandleTouchHandler (object sender, System.EventArgs e)
{
OVRTouchpad.TouchArgs touchArgs = (OVRTouchpad.TouchArgs)e;
if(touchArgs.TouchType == OVRTouchpad.TouchEvent.SingleTap)
{
cam.transform.position = new Vector3(-100f, -100f, -100f);
}
}
My script is attached to the OVRPlayerController

You can't move the VR Camera, it's the SDK that determine the Camera position.
In order to move your camera you can just make a new GameObject as a parent of your Cam then move the parent GameObject (here ParentCamera):
public GameObject ParentCamera;
void Update()
{
if (Input.GetMouseButton (0))
{
cam.transform.position = new Vector3(-100f, -100f, -100f);
}
}

Related

How can I respawn the object again after player collides with it?

I want to respawn object at a new position immediately after player collides with it.
For now my code just spawn the object after respawn time and destroy the previous object.
The code on my empty object on unity2d is
public GameObject point;
private Vector2 screenBounds;
public float respawnTime = 10f;
GameObject star;
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
spawnStar();
StartCoroutine(starWave());
}
public void spawnStar()
{
Debug.Log("Yeah it works");
star = Instantiate(point) as GameObject;
star.transform.position = new Vector2(Random.Range(-screenBounds.x, screenBounds.x), Random.Range(-screenBounds.y, screenBounds.y));
}
IEnumerator starWave()
{
while (true)
{
yield return new WaitForSeconds(respawnTime);
Destroy(star);
spawnStar();
}
}
And the script on object prefab is
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Player")
{
Debug.Log("this is star collider destory");
Destroy(this.gameObject);
}
}
Spawner script
public GameObject point;
void Start()
{
spawnStar();
}
public void spawnStar()
{
Debug.Log("Yeah it works");
star = Instantiate(point) as GameObject;
}
Prefab script
// how long before our star moves
private timeBeforeMoving = 10f;
// our current time
private currentTimer = 0.0f;
// the screen size
private Vector2 screenBounds;
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
transform.position = GenerateNewPosition();
}
private void Update()
{
// increase the time that has passed
currentTimer += Time.deltaTime;
// we have reached the timer threshold, so move the star
if(currentTimer >= timeBeforeMoving)
{
MoveOurStar();
}
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Player")
{
MoveOurStar();
}
}
private void MoveOurStar()
{
// reset the timer as we just moved
currentTimer = 0.0f;
transform.position = GenerateNewPosition();
}
private Vector2 GenerateNewPosition()
{
return new Vector2(Random.Range(-screenBounds.x, screenBounds.x), Random.Range(-screenBounds.y, screenBounds.y));;
}
Instead of destroying it run your randomize position code again. If you do not want it spawning in the same location as the player, you can use a circle cast to determine if the new location the object will spawn is still on top of the player. If it is, just randomly pick a new location again.
If you do not want to put your spawn code inside of the star script when you create the star you can set a delegate callback in the star script to call back to the script that is spawning it letting it know it needs to be moved. Or make the spawner a singleton or even implement an eventsystem to fire an event when the object is destroyed letting the manager know to move that specific object.
If you would like to just go with the example code snippet I provided and are having trouble implementing the circle cast, let me know and I can provide another snippet.
Edit: I changed the code around a bit. Now the spawner will just spawn a single star and the star handles where it moves after it collides.

Camera Rotate with Player Unity 3D

I have a ball that move forward and bounce and rotate, and I want the camera to follow it and rotate with it so the camera always look at the ball from behind. So I made the script bellow but the camera didn't look at the ball when rotating!
NB: I didn't use camera as a child of the ball because I don't want the camera to bounce.
Camera Script:
public Transform Ball;
private Vector3 Offset;
// Use this for initialization
void Start () {
Offset = transform.position - Ball.transform.position;
}
// Update is called once per frame
void LateUpdate () {
transform.position = new Vector3(Ball.transform.position.x + Offset.x, transform.position.y, Ball.transform.position.z + Offset.z);
transform.rotation = Ball.transform.rotation;
}
[SerializeField]
private Transform target;
[SerializeField]
private Vector3 offsetPosition;
[SerializeField]
private Space offsetPositionSpace = Space.Self;
[SerializeField]
private bool lookAt = true;
private void Update()
{
Refresh();
}
public void Refresh()
{
if(target == null)
{
Debug.LogWarning("Missing target ref !", this);
return;
}
// compute position
if(offsetPositionSpace == Space.Self)
{
transform.position = target.TransformPoint(offsetPosition);
}
else
{
transform.position = target.position + offsetPosition;
}
// compute rotation
if(lookAt)
{
transform.LookAt(target);
}
else
{
transform.rotation = target.rotation;
}
}
The target is your player gameobject

Moving UI with Screen Space - Camera (Unity)

I want to move an image UI when Canvas is set on Screen Space - Camera
However, nothing seems to work. I've tried the following things:
public void OnDrag(PointerEventData eventData)
{
Vector3 screenPoint = Input.mousePosition;
screenPoint.z = 0.13f; //distance of the plane from the camera
icon.transform.position = Camera.main.ScreenToWorldPoint(screenPoint);
}
Makes the image move out of the screen instantly.
public GameObject Target;
private EventTrigger _eventTrigger;
void Start ()
{
_eventTrigger = GetComponent<EventTrigger>();
_eventTrigger.AddEventTrigger(OnDrag, EventTriggerType.Drag);
}
void OnDrag(BaseEventData data)
{
PointerEventData ped = (PointerEventData) data;
Target.transform.Translate(ped.delta);
}
same story, image dissapires and moves out of the screen.
public void OnDrag(PointerEventData eventData)
{
Vector3 clickedPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
InventoryParent.transform.position = clickedPosition;
}
as the above.
Anyone has idea on how can I do accurate mouse dragging UI with Screen-Space Camera? Doing it with overlay works fine.
Change your UI element RectTransform anchors to:
and add this script to your UI element object:
RectTransform rectT;
void Start()
{
EventTrigger trigger = GetComponent<EventTrigger>();
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = EventTriggerType.Drag;
entry.callback.AddListener((data) => { OnDragDelegate((PointerEventData)data); });
trigger.triggers.Add(entry);
rectT = GetComponent<RectTransform>();
}
public void OnDragDelegate(PointerEventData data)
{
rectT.anchoredPosition = data.position;
}
You also need the EventTrigger component on your UI element object.

How to bringback an object to its original position after rotation in unity?

I have created a project where a cube is rotated when we touch on it. I want the cube to return back to its original position when the user stops touching the cube. Below I have added the source code of rotating a cube:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshRenderer))]
public class dr : MonoBehaviour
{
#region ROTATE
private float _sensitivity = 1f;
private Vector3 _mouseReference;
private Vector3 _mouseOffset;
private Vector3 _rotation = Vector3.zero;
private bool _isRotating;
#endregion
void Update()
{
if(_isRotating)
{
// offset
_mouseOffset = (Input.mousePosition - _mouseReference); // apply rotation
_rotation.y = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity; // rotate
gameObject.transform.Rotate(_rotation); // store new mouse position
_mouseReference = Input.mousePosition;
}
}
void OnMouseDown()
{
// rotating flag
_isRotating = true;
// store mouse position
_mouseReference = Input.mousePosition;
}
void OnMouseUp()
{
// rotating flag
_isRotating = false;
}
}
edited code:-
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshRenderer))]
public class pt : MonoBehaviour
{
#region ROTATE
private float _sensitivity = 1f;
private Vector3 _mouseReference;
private Vector3 _mouseOffset;
private Vector3 _rotation = Vector3.zero;
private bool _isRotating;
private Quaternion original;
#endregion
void start(){
original = transform.rotation;
}
void Update()
{
if(_isRotating)
{
// offset
_mouseOffset = (Input.mousePosition - _mouseReference); // apply rotation
_rotation.y = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity; // rotate
gameObject.transform.Rotate(_rotation); // store new mouse position
_mouseReference = Input.mousePosition;
}
}
public void OnMouseDown()
{
// rotating flag
_isRotating = true;
// store mouse position
_mouseReference = Input.mousePosition;
}
public void OnMouseUp()
{
// rotating flag
_isRotating = false;
transform.rotation = original;
}
}
"im trying to rotate a 3d model of a sofa and return to its starting rotation.but if i used this code " whenever if i stopped touching the sofa , it turns to **backside of sofa"**
i want it to return to initial rotation.u can see initally this is how the sofa looks like and if i stopped touching it returns to its backside of sofa. i want it to return to its front side again if i stopped rotation
I want the cube to return back to its original position when the user
stopped touching the cube
I can't exactly tell which part of this you are struggling with but you can simply get the position of the GameObject in the Start or Awake function then set the transform.position to that value when OnMouseUp is called.
private Vector3 originalPos;
void Start()
{
//Get the original position
originalPos = transform.position;
}
void OnMouseUp()
{
_isRotating = false;
//Reset GameObject to the original position
transform.position = originalPos;
}
EDIT:
For rotation, it is also the-same thing. Just use Quaternion and transform.rotation instead of Vector3 and transform.position.
private Quaternion originalPos;
void Start()
{
//Get the original rotation
originalPos = transform.rotation;
}
void OnMouseUp()
{
_isRotating = false;
//Reset GameObject to the original rotation
transform.rotation = originalPos;
}
You still have to incorporate that into the original code from your answer. If this is something you can't do then consider watching Unity's scripting tutorial here.

Unity2D: How to check if a sprite is clicked/touched

I am making a 2D platformer in Unity for iOS, and I need to make buttons so the user can move, but for some reason, the script I made is not working. Also, the script I am putting in is just for the Left button, but the Right and Jump scripts work the same way.
Code:
using UnityEngine;
using System.Collections;
public class Left : MonoBehaviour {
public GameObject player;
public GameObject button;
void Start () {
}
void Update () {
if (Input.GetKey (KeyCode.A)) {
player.GetComponent<PlayerAnimator>().animationState = MovementState.moveLeft;
player.transform.position+=Vector3.left / 30;
}
if (Input.touchCount > 0){
foreach(Touch touch in Input.touches){
Collider2D col = button.GetComponent<Collider2D>();
Vector3 tpos = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 0));
if(col.bounds.Contains(tpos)){
Debug.Log ("left");
player.GetComponent<PlayerAnimator>().animationState = MovementState.moveLeft;
player.transform.position+=Vector3.left / 30;
}
}
}
}
void OnMouseOver(){
Debug.Log ("left");
player.GetComponent<PlayerAnimator>().animationState = MovementState.moveLeft;
player.transform.position+=Vector3.left / 30;
}
void OnMouseUp(){
player.GetComponent<PlayerAnimator> ().animationState = MovementState.idleLeft;
}
}
Don't use OnMouseOver for android application. It isn't usable on touch devices. But instead of it, OnMouseDrag function will work.
void OnMouseDrag(){
Debug.Log ("left");
player.GetComponent<PlayerAnimator>().animationState = MovementState.moveLeft;
player.transform.position+=Vector3.left / 30;
}
Edit: Because OnMouseOver is called when position of mouse is over object but not clicked. Otherwise OnMouseDrag is called when position of mouse is over object and clicked. In mobile devices OnMouseOver situation isn't possible.

Categories