Switch device camera in Unity 3d - image

I am using WebCamTexture class to open camera from device. I want to switch camera from front to back and vice versa in between the game play. Can anybody help?
WebCamDevice[] devices = WebCamTexture.devices;
WebCamTexture webCamTexture = new WebCamTexture(devices[1].name);
renderer.material.mainTexture = webCamTexture;
webCamTexture.filterMode = FilterMode.Trilinear;
webCamTexture.Play();
This opens my front camera. But I can't switch the camera.

I got the solution. You just need to set the name of the device. By default back camera is "Camera 0" and "Camera 1" front camera. First Stop your camera , change the set device.
if (devices.Length > 1) {
webCamTexture.Stop();
if (frontCamera == true)
{
webCamTexture.deviceName = devices[0].name;
frontCamera = false;
}
else
{
webCamTexture.deviceName = devices[1].name;
frontCamera = true;
}
webCamTexture.Play ();
}

I have used the following code for switching the front and back camera of the iPhone Device using C# script
WebCamDevice[] devices;
public WebCamTexture mCamera = null;
public GameObject plane; // this is the object where i am going to show the camera
// Use this for initialization
void Start ()
{
devices = WebCamTexture.devices;
plane = GameObject.FindWithTag ("Player");
mCamera = new WebCamTexture (Screen.width,Screen.height);
mCamera.deviceName = devices[0].name; // Front camera is at Index 1 and Back Camera is at Index 0
plane.renderer.material.mainTexture = mCamera;
mCamera.Play ();
}
the above code will show the back Camera when the Scene is loaded ,for accessing the front camera on the click of front button defined below
if (GUI.Button (new Rect (100, 1000, 120, 40), "Front"))
{
if(devices.Length>1)
{
mCamera.Stop();
mCamera.deviceName = (mCamera.deviceName == devices[0].name) ? devices[1].name : devices[0].name;
mCamera.Play();
}
}
This is button, by clicking it will redirect to front camera and again clicking it will redirect to back camera alternatively

if (devices.Length > 1) {
webCamTexture.Stop();
if (frontCamera == true)
{
webCamTexture.deviceName = devices[0].name;
frontCamera = WebCamTexture.devices[0].isFrontFacing;
}
else
{
webCamTexture.deviceName = devices[1].name;
frontCamera = WebCamTexture.devices[1].isFrontFacing;
}
webCamTexture.Play ();
}
We've used Camera Capture Kit for a social image sharing game/app to do a similar functionality to what you are describing, The other solution presented here is not 100% solid, since there might potentially be devices with different order of front and back-facing devices.

Related

Potree Zoom in/out on click

I am trying to zoom in/out when the user clicks the “+” or “-” buttons on my control panel. I got it to move left, right, up, down with the “tweenFunction” and it worked. I’ve tried
viewer.scene.camera.zoom += 0.1;
Which didn’t work for me because I don’t have the “camera” variable in my code, only the viewer. Here is my code
setup();
window.viewer = new Potree.Viewer(document.getElementById("potree_render_area"));
viewer.setEDLEnabled(false);
viewer.setFOV(60);
viewer.setPointBudget(5*1000*1000);
document.title = "";
viewer.setBackground("gradient"); // ["skybox", "gradient", "black", "white"];
viewer.loadSettingsFromURL();
viewer.loadGUI(() => {
viewer.setLanguage('en');
$("#menu_scene").next().show();
//viewer.toggleSidebar();
});
viewer.setDescription(`
`);
let sceneSG = new Potree.Scene();
let sceneSG2 = new Potree.Scene();
viewer.setScene(sceneSG);
Potree.loadPointCloud("model.js", "model", function (e){
sceneSG.addPointCloud(e.pointcloud);
sceneSG.view.position.set(37.812, -26.781, 51.178);
sceneSG.view.lookAt(new THREE.Vector3(-53.587, 33.834, 28.864));
let material = e.pointcloud.material;
material.size = 1;
material.pointSizeType = Potree.PointSizeType.ADAPTIVE;
});
you can't access "directly" to viewer.scene.camera because potree has two cameras (a perspective one and an orthographic). But you can access to the active camera with this function:
viewer.scene.getActiveCamera()
So if you want to zoom in, it could look like this:
var myactivecamera = viewer.scene.getActiveCamera();
myactivecamera.zoom += 0.1;

Stop rotating for a click right on the game object

I have a unity game and in it, a rotating game object, which increases its speed when it is clicked.
My problem is that the game does not work as I want it to. Right now, if I click any part of the screen, it increases the game object's speed of rotation. On the other hand, if I keep my finger on the screen, the game object starts to slow down and then starts rotating in the opposite direction.
I want the rotation of the object to increase when I click on it, not just if I click on any part of the screen. Furthermore, I don't know why holding down reverses the direction of rotation.
var speed = 1;
var click = 0;
Screen.orientation = ScreenOrientation.LandscapeLeft;
function Update (){
{
transform.Rotate(0,0,speed);
}
if(Input.GetMouseButton(0))
{
if(speed != 0)
{
speed = 0;
} else {
click++;
speed = click;
}
You must use Input.GetMouseButtonUp or Input.GetMouseButtonDown, NOT A Input.GetMouseButton, this method used for clamping.
Try use this code:
var speed = 1;
var click = 0;
Screen.orientation = ScreenOrientation.LandscapeLeft;
function Update (){
{
transform.Rotate(0,0,speed);
}
if(Input.GetMouseButtonDown(0))
{
if(speed != 0)
{
speed = 0;
} else {
click++;
speed = click;
}
A few issues here:
Firstly:
To increase speed upon clicking on the object only, use raycasting from camera, and check if it hits your object. Your object needs need a collider component on it for this to work.
RaycastHit hit;
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
Transform objectHit = hit.transform;
objectHit.Rotate(0,0,speed);
}
Refer to https://docs.unity3d.com/Manual/CameraRays.html -> Raycasting section, for more information.
Secondly:
Input.GetMouseButtonDown(..) // returns true at the instance your mouse button transits from up to down
Input.GetMouseButton(..) // returns true as long as your mouse button is held down
Use Input.GetMouseButtonDown(..) in your Update() method if you want to to do something when you click on it.

Scale UI for multiple resolutions/different devices

I have a quite simple unity GUI that has the following scheme :
Where Brekt and so are buttons.
The GUI works just fine on PC and is on screen space : overlay so it is supposed to be adapted automatically to fit every screen.
But on tablet the whole GUI is smaller and reduced in the center of the screen, with huge margins around the elements (can't join a screenshot now)
What is the way to fix that? Is it something in player settings or in project settings?
Automatically scaling the UI requires using combination of anchor,pivot point of RecTransform and the Canvas Scaler component. It is hard to understand it without images or videos. It is very important that you thoroughly understand how to do this and Unity provided full video tutorial for this.You can watch it here.
Also, when using scrollbar, scrollview and other similar UI controls, the ContentSizeFitter component is also used to make sure they fit in that layout.
There is a problem with MovementRange. We must scale this value too.
I did it so:
public int MovementRange = 100;
public AxisOption axesToUse = AxisOption.Both; // The options for the axes that the still will use
public string horizontalAxisName = "Horizontal"; // The name given to the horizontal axis for the cross platform input
public string verticalAxisName = "Vertical"; // The name given to the vertical axis for the cross platform input
private int _MovementRange = 100;
Vector3 m_StartPos;
bool m_UseX; // Toggle for using the x axis
bool m_UseY; // Toggle for using the Y axis
CrossPlatformInputManager.VirtualAxis m_HorizontalVirtualAxis; // Reference to the joystick in the cross platform input
CrossPlatformInputManager.VirtualAxis m_VerticalVirtualAxis; // Reference to the joystick in the cross platform input
void OnEnable()
{
CreateVirtualAxes();
}
void Start()
{
m_StartPos = transform.position;
Canvas c = GetComponentInParent<Canvas>();
_MovementRange = (int)(MovementRange * c.scaleFactor);
Debug.Log("Range:"+ _MovementRange);
}
void UpdateVirtualAxes(Vector3 value)
{
var delta = m_StartPos - value;
delta.y = -delta.y;
delta /= _MovementRange;
if (m_UseX)
{
m_HorizontalVirtualAxis.Update(-delta.x);
}
if (m_UseY)
{
m_VerticalVirtualAxis.Update(delta.y);
}
}
void CreateVirtualAxes()
{
// set axes to use
m_UseX = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyHorizontal);
m_UseY = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyVertical);
// create new axes based on axes to use
if (m_UseX)
{
m_HorizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(horizontalAxisName);
CrossPlatformInputManager.RegisterVirtualAxis(m_HorizontalVirtualAxis);
}
if (m_UseY)
{
m_VerticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(verticalAxisName);
CrossPlatformInputManager.RegisterVirtualAxis(m_VerticalVirtualAxis);
}
}
public void OnDrag(PointerEventData data)
{
Vector3 newPos = Vector3.zero;
if (m_UseX)
{
int delta = (int)(data.position.x - m_StartPos.x);
delta = Mathf.Clamp(delta, -_MovementRange, _MovementRange);
newPos.x = delta;
}
if (m_UseY)
{
int delta = (int)(data.position.y - m_StartPos.y);
delta = Mathf.Clamp(delta, -_MovementRange, _MovementRange);
newPos.y = delta;
}
transform.position = new Vector3(m_StartPos.x + newPos.x, m_StartPos.y + newPos.y, m_StartPos.z + newPos.z);
UpdateVirtualAxes(transform.position);
}

Changing alpha of Text's CanvasGroup in OnTriggerEnter Unity

I'm currently working on a game that pays hommage to Marble Blast Gold/Ultra.
At this point I have text that is positioned with the marble. The text is a child of a canvas and I have a canvas group added to the text. I initially set the alpha of the canvas group to 0 so that you can't see the text.
What I'm trying to do is have it so that when you pick up a power up the text reappears by changing the canvas group's alpha back to 1 and then once the power up is used set it back to 0.
I'm not seeming to have any luck with my current code.
// Super Jump pickup
if (col.gameObject.tag == "Spring")
{
superJumpText.GetComponent<CanvasGroup>().alpha = 1;
canSuperJump = true;
canSuperSpeed = false;
col.gameObject.SetActive(false);
hitSuperJump = true;
Invoke("Display", 20);
}
void Update()
{
//super jump
if (canSuperJump)
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Vector3 jump = new Vector3(0, superJumpForce, 0);
GetComponent<Rigidbody>().AddForce(jump);
canSuperJump = false;
superJumpText.GetComponent<CanvasGroup>().alpha = 0;
}
}
}
The only reason this would not work for you is that somewhere in your parent hierarchy you have a gameobject with another canvas group. That would ALWAYS override the child canvas group settings UNLESS you select the 'Ignore Parent Groups' checkbox in the child canvas

In Android Maps V2, is there a way to control the positioning of the map when a marker is tapped on?

Currently, by default, when tapping a marker, the map centers on the marker. Is there a way to control that, introduce some offset values. I have a popup info window that is a little taller at times and I would like to position the map so it does not get cut off at the top.
You could likely override the GoogleMap marker click event and adjust the camera there.
For example
Maker lastOpened = null;
mMap.setOnMarkerClickListener(new OnMarkerClickListener() {
public boolean onMarkerClick(Marker marker) {
// Check if there is an open info window
if (lastOpened != null) {
// Close the info window
lastOpened.hideInfoWindow();
// Is the marker the same marker that was already open
if (lastOpened.equals(marker)) {
// Nullify the lastOpened object
lastOpened = null;
// Return so that the info window isn't opened again
return true;
}
}
// Open the info window for the marker
marker.showInfoWindow();
// Re-assign the last opened such that we can close it later
lastOpened = marker;
// Get the markers current position
LatLng curMarkerPos = marker.getPosition();
// Use the markers position to get a new latlng to move the camera to such that it adjusts appropriately to your infowindows height (might be more or less then 0.3 and might need to subtract vs add this is just an example)
LatLng camMove = new LatLng(curMarkerPos.latitude + 0.3, curMarkerPos.longitude);
// Create a camera update with the new latlng to move to
CameraUpdate camUpdate = CameraUpdateFactory.newLatLng(camMove);
// Move the map to this position
mMap.moveCamera(camUpdate);
// Event was handled by our code do not launch default behaviour.
return true;
}
});
mMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
if (lastOpened != null) {
// Hide the last opened
lastOpened.hideInfoWindow();
// Nullify lastOpened
lastOpened == null;
}
// Move the camera to the new position
final CameraPosition cameraPosition = new CameraPosition.Builder().target(point).zoom(mMap.getCameraPosition().zoom).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
});
This code hasnt been tested but should at least give you a great start at it. The default behavior of onMarkerClick is to move the camera and open the info window. So overriding this and implementing your own should allow you to move the camera where u please.
Thanks, DMan
I modified the really nice answer above for anyone who just wants to remove the move-to-center default behavior of the marker click:
Add this to setUpMap():
mMap.setOnMarkerClickListener(getMarkerClickListener());
And then add method:
Marker lastOpened = null;
public OnMarkerClickListener getMarkerClickListener() {
return new OnMarkerClickListener() {
public boolean onMarkerClick(Marker marker) {
if (lastOpened != null) {
lastOpened.hideInfoWindow();
if (lastOpened.equals(marker)) {
lastOpened = null;
return true;
}
}
marker.showInfoWindow();
lastOpened = marker;
return true;
}
};
}

Resources