I am creating a character customization system. I have 2 shirts with their own 2 textures.
When I switch shirts the all of the textures are applying two both renderers instead of their own.
Any help would be appreciated. Here is my script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharCustomizationOne : MonoBehaviour
{
public GameObject[] characters;
public GameObject[] maleHairs;
public GameObject[] maleShirts;
public GameObject[] malePants;
public GameObject[] femaleHairs;
public GameObject[] femaleShirts;
public GameObject[] femalePants;
public Texture[] charTexturesM;
public Texture[] charTexturesF;
public Texture[] shirtTextureM;
public Texture[] shirtTextureF;
public Texture[] pantTextureM;
public Texture[] pantTextureF;
private int currentCharacters;
private int currentMaleHair;
private int currentMaleShirts;
private int currentMalePants;
private int currentFemaleHair;
private int currentFemaleShirt;
private int currentFemalePant;
private int currentCharTextureM;
private int currentCharTextureF;
private int currentShirtTextureM;
private int currentShirtTextureF;
private int currentPantTextureM;
private int currentPantTextureF;
public Renderer rendererM;
public Renderer rendererF;
public Renderer[] rendererShirtM = new Renderer[2];
public Renderer[] rendererShirtF = new Renderer[2];
public Renderer[] rendererPantM = new Renderer[2];
public Renderer[] rendererPantF = new Renderer[2];
public void Update() {
//Gender Loop
for (int i = 0; i < characters.Length; i++)
{
if (i == currentCharacters)
{
characters[i].SetActive(true);
}
else
{
characters[i].SetActive(false);
}
}
//Hair Loop
if (currentCharacters == 0)
{
for (int i = 0; i < maleHairs.Length; i++)
{
if (i == currentMaleHair)
{
femaleHairs[i].SetActive(false);
maleHairs[i].SetActive(true);
}
else
{
femaleHairs[i].SetActive(false);
maleHairs[i].SetActive(false);
}
}
}
else
{
for (int i = 0; i < femaleHairs.Length; i++)
{
if (i == currentFemaleHair)
{
maleHairs[i].SetActive(false);
femaleHairs[i].SetActive(true);
}
else
{
maleHairs[i].SetActive(false);
femaleHairs[i].SetActive(false);
}
}
}
// Shirt Loop
if (currentCharacters == 0)
{
for (int i = 0; i < maleShirts.Length; i++)
{
if (i == currentMaleShirts)
{
femaleShirts[i].SetActive(false);
maleShirts[i].SetActive(true);
}
else
{
femaleShirts[i].SetActive(false);
maleShirts[i].SetActive(false);
}
}
}
else
{
for (int i = 0; i < femaleShirts.Length; i++)
{
if (i == currentFemaleShirt)
{
maleShirts[i].SetActive(false);
femaleShirts[i].SetActive(true);
}
else
{
maleShirts[i].SetActive(false);
femaleShirts[i].SetActive(false);
}
}
}
// Pants Loop
if (currentCharacters == 0)
{
for (int i = 0; i < malePants.Length; i++)
{
if (i == currentMalePants)
{
femalePants[i].SetActive(false);
malePants[i].SetActive(true);
}
else
{
femalePants[i].SetActive(false);
malePants[i].SetActive(false);
}
}
}
else
{
for (int i = 0; i < femalePants.Length; i++)
{
if (i == currentFemalePant)
{
malePants[i].SetActive(false);
femalePants[i].SetActive(true);
}
else
{
malePants[i].SetActive(false);
femalePants[i].SetActive(false);
}
}
}
//CharTexture Loop
if (currentCharacters == 0)
{
for (int i = 0; i < charTexturesM.Length; i++)
{
if (i == currentCharTextureM)
{
rendererM.sharedMaterial.mainTexture = charTexturesM[i];
}
}
}
else
{
for (int i = 0; i < charTexturesF.Length; i++)
{
if (i == currentCharTextureF)
{
rendererF.sharedMaterial.mainTexture = charTexturesF[i];
}
}
}
//Shirt Texture Loop
if (currentCharacters == 0)
{
for (int i = 0; i < maleShirts.Length; i++)
{
for (int j = 0; j < shirtTextureM.Length; j++)
{
if (j == currentShirtTextureM)
{
rendererShirtM[i].sharedMaterial.mainTexture = shirtTextureM[j];
}
}
}
}
else
{
for (int i = 0; i < femaleShirts.Length; i++)
{
for (int j = 0; j < shirtTextureF.Length; j++)
{
if (j == currentShirtTextureF)
{
rendererShirtF[i].sharedMaterial.mainTexture = shirtTextureF[j];
}
}
}
}
//Pant Texture Loop
if (currentCharacters == 0)
{
for (int i = 0; i < malePants.Length; i++)
{
for (int j = 0; j < pantTextureM.Length; j++)
{
if (j == currentPantTextureM)
{
rendererPantM[i].sharedMaterial.mainTexture = pantTextureM[j];
}
}
}
}
else
{
for (int i = 0; i < femalePants.Length; i++)
{
for (int j = 0; j < pantTextureF.Length; j++)
{
if (j == currentPantTextureF)
{
rendererPantF[i].sharedMaterial.mainTexture = pantTextureF[j];
}
}
}
}
}
//Switching Characters
public void SwitchCharacters() {
Debug.Log("Method Called!");
if (currentCharacters == characters.Length - 1)
{
currentCharacters = 0;
}
else
{
currentCharacters++;
}
}
//Switching Hairs
public void SwitchHairs() {
Debug.Log("MaleHairsCalled");
if (currentMaleHair == maleHairs.Length - 1)
{
currentMaleHair = 0;
}
else
{
currentMaleHair++;
}
if (currentFemaleHair == femaleHairs.Length - 1)
{
currentFemaleHair= 0;
}
else
{
currentFemaleHair++;
}
}
//Switching Shirts
public void SwitchShirts()
{
Debug.Log("MaleShirtCalled");
if (currentMaleShirts == maleShirts.Length - 1)
{
currentMaleShirts = 0;
}
else
{
currentMaleShirts++;
}
if (currentFemaleShirt == femaleShirts.Length - 1)
{
currentFemaleShirt = 0;
}
else
{
currentFemaleShirt++;
}
}
//Switching Pants
public void SwitchPants() {
Debug.Log("MalePantsCalled");
if (currentMalePants == malePants.Length - 1)
{
currentMalePants = 0;
}
else
{
currentMalePants++;
}
if (currentFemalePant == femalePants.Length - 1)
{
currentFemalePant = 0;
}
else
{
currentFemalePant++;
}
}
//Switching Character Textures
public void SwitchCharTexture()
{
Debug.Log("Char Texture Method Was Called!");
if (currentCharTextureM == charTexturesM.Length - 1)
{
currentCharTextureM = 0;
}
else
{
currentCharTextureM++;
}
if (currentCharTextureF == charTexturesF.Length - 1)
{
currentCharTextureF = 0;
}
else
{
currentCharTextureF++;
}
}
public void SwitchShirtTexture()
{
Debug.Log("Shirt Texture Method Was Called!");
if (currentShirtTextureM == shirtTextureM.Length - 1)
{
currentShirtTextureM = 0;
}
else
{
currentShirtTextureM++;
}
if (currentShirtTextureF == shirtTextureF.Length - 1)
{
currentShirtTextureF = 0;
}
else
{
currentShirtTextureF++;
}
}
public void SwitchPantTexture()
{
Debug.Log("Pant Texture Method Was Called!");
if (currentPantTextureM == pantTextureM.Length - 1)
{
currentPantTextureM = 0;
}
else
{
currentPantTextureM++;
}
if (currentPantTextureF == pantTextureF.Length - 1)
{
currentPantTextureF = 0;
}
else
{
currentPantTextureF++;
}
}
//End of Class
}
instead of Renderer.sharedMaterial
Modifying sharedMaterial will change the appearance of all objects using this material, and change material settings that are stored in the project too.
It is not recommended to modify materials returned by sharedMaterial. If you want to modify the material of a renderer use material instead.
rather use Renderer.material
Modifying material will change the material for this object only.
If the material is used by any other renderers, this will clone the shared material and start using it from now on.
Also check your loops .. some things seems odd there e.g.
for (int j = 0; j < someTextureArray.Length; j++)
{
if (j == currentTextureIndex)
{
someRenderer[i].material.mainTexture = someTextureArray[j];
}
}
seems just to be a very complex way of simply writing
someRenderer[i].material.mainTexture = someTextureArray[currentTextureIndex];
For all your switch methods: note that the easiest solution for wrap around a positive counter for indices in an array you can simply do
currentIndex = (currentIndex + 1) % accordingArray.Length;
Related
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;
}
}
In my project I need to detect multiple gestures, I made a .gbd file with 2 continuous gestures. I can detect the continuous gesture when the .gbd file had one gesture. When there is 2 gestures I am unable to read any one gesture. Do any one know the reason? Here I post my code. I used Body basics example from sdk, and added necessary functions separately to avoid memory leakage.
//separate function to initialize database, vgb frame source and vgb frame reader
void CBodyBasics::InitializeVGB()
{
HRESULT hr;
std::wstring sDbFile = L"ContinuousGestures.gbd";
hr = CreateVisualGestureBuilderDatabaseInstanceFromFile(sDbFile.c_str(), &m_pGestureDatabase);
if (SUCCEEDED(hr))
{
OutputDebugString(L"Success DB\n");
}
else
{
OutputDebugString(L"Failure DB\n");
}
for (int i = 0; i < BODY_COUNT; i++)
{
// Source
hr = CreateVisualGestureBuilderFrameSource(m_pKinectSensor, 0, &m_pVGBFrameSource[i]);
if (SUCCEEDED(hr))
{
OutputDebugString(L"Source created\n");
}
else
{
OutputDebugString(L"Soure creation failed\n");
}
// Reader
hr = m_pVGBFrameSource[i]->OpenReader(&m_pVGBFrameReader[i]);
if (SUCCEEDED(hr))
{
OutputDebugString(L"reader opened\n");
}
else
{
OutputDebugString(L"No reader\n");
}
}
}
//function to find the available gesture count, add the available gestures to source
void CBodyBasics::CheckGestureMultiple()
{
HRESULT hr;
hr = m_pGestureDatabase->get_AvailableGesturesCount(&iGestureCount);
//gesture count
if (SUCCEEDED(hr))
{
OutputDebugString(L"gesture #\n");
}
else
{
OutputDebugString(L"0 gesture\n");
}
StringCchPrintf(smessage, _countof(smessage), L"Gesture Count %d \n", iGestureCount);
OutputDebugString(smessage);
hr = m_pGestureDatabase->get_AvailableGestures(iGestureCount, m_pgesturelist);
//gesture list
if (SUCCEEDED(hr) && m_pgesturelist != nullptr)
{
OutputDebugString(L"received available gestures\n");
GestureType mtype;
WCHAR sName[260];
for (int i = 0; i < iGestureCount; ++i)
{
hr = m_pgesturelist[i]->get_GestureType(&mtype);
//gesture type
if (SUCCEEDED(hr))
{
OutputDebugString(L"gesture type\n");
if (mtype == GestureType_Discrete)
{
OutputDebugString(L"discrete\n");
}
else if (mtype == GestureType_Continuous)
{
OutputDebugString(L"continuous\n");
}
}
else
{
OutputDebugString(L"no gesture type\n");
}
hr = m_pgesturelist[i]->get_Name(260, sName);
//gesture name
if (SUCCEEDED(hr))
{
OutputDebugString(L"gesture name\n");
StringCchPrintf(smessage, _countof(smessage), L"%s \t %d \n", sName, i);
OutputDebugString(smessage);
}
else
{
OutputDebugString(L"no name\n");
}
}
}
else
{
OutputDebugString(L"not received gestures\n");
}
for (int i = 0; i < BODY_COUNT; ++i)
{
//add gestures to the source
hr = m_pVGBFrameSource[i]->AddGestures(iGestureCount, m_pgesturelist);
if (SUCCEEDED(hr))
{
OutputDebugString(L"Gesture added\n");
}
else
{
OutputDebugString(L"not added\n");
}
}
}
//function to read the vgb frame and process if the gesture is detected
void CBodyBasics::ReadVGBFrameMultiple(int t_bodyCount)
{
HRESULT hr;
for (int i = 0; i < t_bodyCount; i++)
{
hr = m_pVGBFrameReader[i]->CalculateAndAcquireLatestFrame(&m_pVGBFrame);
if (SUCCEEDED(hr) && m_pVGBFrame != nullptr)
{
OutputDebugString(L"vgb frame\n");
BOOLEAN bGestureTracked = false;
hr = m_pVGBFrame->get_IsTrackingIdValid(&bGestureTracked);
if (SUCCEEDED(hr) && bGestureTracked)
{
OutputDebugString(L"valid gesture id and gesture tracked\n");
GestureType gesturetype;
m_pgesturelist[i]->get_GestureType(&gesturetype);
switch (gesturetype)
{
case GestureType::GestureType_Discrete:
hr = m_pVGBFrame->get_DiscreteGestureResult(m_pgesturelist[i], &m_pDiscreteResult);
if (SUCCEEDED(hr) && m_pDiscreteResult != nullptr)
{
OutputDebugString(L"discrete result\n");
BOOLEAN bDetected = false;
hr = m_pDiscreteResult->get_Detected(&bDetected);
if (SUCCEEDED(hr) && bDetected)
{
OutputDebugString(L"gesture detected\n");
StringCchPrintf(smessage, _countof(smessage), L"gesture detected %d\n", bDetected);
OutputDebugString(smessage);
float confidence = 0.0f;
hr = m_pDiscreteResult->get_Confidence(&confidence);
if (SUCCEEDED(hr) && confidence != 0.0f)
{
OutputDebugString(L"confidence is detected \t");
//if (confidence > 0.3f)
//{
StringCchPrintf(smessage, _countof(smessage), L"confidence value is %f\n", confidence);
OutputDebugString(smessage);
//}
}
else
{
OutputDebugString(L"no confidence\n");
}
}
else
{
OutputDebugString(L"gesture not detected\n");
}
}
else
{
OutputDebugString(L"no discrete result\n");
}
case GestureType::GestureType_Continuous:
hr = m_pVGBFrame->get_ContinuousGestureResult(m_pgesturelist[i], &m_pContinousResult);
if (SUCCEEDED(hr) && m_pContinousResult != nullptr)
{
OutputDebugString(L"continuous gesture\n");
WCHAR gesturename[100];
hr = m_pgesturelist[i]->get_Name(100, gesturename);
//if (gesturename == L"SwipeLeft")
//{
float progress = 0.0f;
OutputDebugString(L"get progress of continuous gesture \t");
hr = m_pContinousResult->get_Progress(&progress);
if (SUCCEEDED(hr) && progress != 0.0f)
{
StringCchPrintf(smessage, _countof(smessage), L"progress value is %f\n", progress);
OutputDebugString(smessage);
}
//}
}
else
{
OutputDebugString(L"no continuous gesture\n");
}
default:
break;
}
}
else
{
OutputDebugString(L"invalid gesture id\n");
}
}
else
{
OutputDebugString(L"no frame\n");
}
}
}
Is there wrong in my code? Do I need to modify my code? Can anyone help me?
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.
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;
}
}
I have a texture 2d on my gui screen. I want to rotate this texture till +540 and -540 degrees with finger touch rotate. Beyond this limit it should stop rotating.
can any1 help??
I believe that you can't rotate GUI texture. I suppose the best way to do what you want is to assign a plane as a child to camera facing it, and rotate that plane as you want.
public Texture2D steering;
public static TouchControl Instance;
public float angleRotate=0f;
public float carRotation=0f;
public int finger;
private Matrix4x4 savedMatrix;
private float steerAngleRad;
public float steerAngleDeg;
private float steerAngleRadTemp;
public float steerAngleDegTemp;
private float dx=0f;
private float dy=0f;
private int i;
private float newAngle =0f;
private float initAngle;
private float rotationLimit=540f;
public float secondWheelRot=0f;
private float preRotDeg=0f;
private float angleDiff=0f;
private bool clockWheel=false;
private bool onlyOnce=false;
private Vector2 steeringPos;
private Vector2 centre;
private bool inXRange=false;
private bool inYRange=false;
// private bool moving=false;
private float steeringWidth=0f;
private float steeringHeight=0f;
private float gobackSpeed=20f;
void Start()
{
Instance=this;
i=0;
finger=3;
steeringPos=new Vector2(Screen.width*0.025f,Screen.height*0.68f);
steeringWidth=Screen.width*0.12f;
steeringHeight=steeringWidth;
centre = new Vector2(steeringPos.x + steeringWidth / 2, steeringPos.y + steeringHeight / 2);
}
void Update()
{
if(Input.touchCount>0 && (!PauseButton.pauseFlag && !DamageBar.Instance.levelLost && !GameTimer.Instance.levelLost && !CommonIndicator.Instance.levelComplete))
{
for(i=0;i< Input.touchCount; ++i)
{
if(Input.GetTouch(i).position.x > 0f && Input.GetTouch(i).position.x < steeringWidth+Screen.width*0.1f)
{
inXRange=true;
}
else
{
inXRange=false;
}
if(Input.GetTouch(i).position.y > 0f && Input.GetTouch(i).position.y < Screen.height-(steeringPos.y))
{
inYRange=true;
}
else
{
inYRange=false;
}
///////////////if touch is in the range/////////////////////
if(inXRange && inYRange)
{
if(Input.GetTouch(i).phase==TouchPhase.Began)
{
finger=Input.touches[i].fingerId;
dx=Input.GetTouch(i).position.x-centre.x;
dy=Input.GetTouch(i).position.y-(Screen.height-centre.y);
steerAngleRadTemp=Mathf.Atan2(dy,dx);
steerAngleDegTemp=-steerAngleRadTemp*Mathf.Rad2Deg;
}
if((Input.GetTouch(i).phase==TouchPhase.Stationary || Input.GetTouch(i).phase==TouchPhase.Moved))
{
preRotDeg=newAngle;
if(preRotDeg<-180f && preRotDeg>-360f)
{
preRotDeg+=360f;
}
if(preRotDeg>180f && preRotDeg<360f)
{
preRotDeg-=360f;
}
dx=Input.GetTouch(i).position.x-centre.x;
dy=Input.GetTouch(i).position.y-(Screen.height-centre.y);
steerAngleRad=Mathf.Atan2(dy,dx);
steerAngleDeg=-steerAngleRad*Mathf.Rad2Deg;
angleRotate=steerAngleDeg-steerAngleDegTemp;
newAngle=angleRotate;
if(newAngle<-180f && newAngle>-360f)
{
newAngle+=360f;
}
if(newAngle>180f && newAngle<360f)
{
newAngle-=360f;
}
if(!onlyOnce)
{
onlyOnce=true;
if(newAngle>preRotDeg)
clockWheel=true;
else
clockWheel=false;
}
if(clockWheel && preRotDeg>0f && newAngle < 0f)
{
clockWheel=true;
}
else if(clockWheel && preRotDeg<0f && newAngle >0f)
{
clockWheel=true;
}
else if(!clockWheel && preRotDeg>0f && newAngle <0f)
{
clockWheel=false;
}
else if(!clockWheel && preRotDeg<0f && newAngle >0f)
{
clockWheel=false;
}
else if(newAngle>preRotDeg)
{
clockWheel=true;
}
else if(newAngle<preRotDeg)
{
clockWheel=false;
}
if(Mathf.Abs(newAngle)>Mathf.Abs(preRotDeg))
{
angleDiff=Mathf.Abs(newAngle)-Mathf.Abs(preRotDeg);
}
else
{
angleDiff=Mathf.Abs(preRotDeg)-Mathf.Abs(newAngle);
}
if(clockWheel)
{
carRotation+=angleDiff;
secondWheelRot+=angleDiff;
if(secondWheelRot>rotationLimit)
{
secondWheelRot=rotationLimit;
}
}
else
{
carRotation-=angleDiff;
secondWheelRot-=angleDiff;
if(secondWheelRot<-rotationLimit)
{
secondWheelRot=-rotationLimit;
}
}
}
// else
// {
// steeringToZero();
// }
if(Input.GetTouch(i).phase==TouchPhase.Ended)// && Input.touches[i].fingerId != AccControl.Instance.finger)
{
onlyOnce=false;
carRotation=0f;
angleRotate=0f;
newAngle=0f;
steeringToZero();
finger=3;
}
}
else if(!AccControl.Instance.onPadTouch && finger==3)
{
steeringToZero();
}
}
}
else if(Input.touchCount==0)
{
steeringToZero();
}
if(Input.touchCount==1 && AccControl.Instance.onPadTouch)
{
steeringToZero();
}
if (Input.GetKeyDown(KeyCode.Escape) && !PauseButton.pauseFlag)
{
Application.LoadLevel("MainMenu");
}
}
void steeringToZero()
{
if(secondWheelRot>0)
{
secondWheelRot-=gobackSpeed/(Input.touchCount+1);
}
else if(secondWheelRot<0)
{
secondWheelRot+=gobackSpeed/(Input.touchCount+1);
}
if(secondWheelRot<gobackSpeed && secondWheelRot>-gobackSpeed)
{
secondWheelRot=0f;
}
}
void OnGUI()
{
savedMatrix = GUI.matrix;
GUIUtility.RotateAroundPivot(carRotation,centre);
GUI.DrawTexture(new Rect(steeringPos.x,steeringPos.y, steeringWidth, steeringHeight), steering);
GUI.matrix = savedMatrix;
}