Inheritance: TaskExtension, Microsoft.Build.Framework.ITask
    void Update()
    {
        // タッチが開始されたら
        if (Input.touchCount > 0)
        {
            this.touch = Input.touches[0];
            // タッチ座標をVector2に変換
            this.touch_point = Camera.main.ScreenToWorldPoint(this.touch.position);

            if (touch.phase == TouchPhase.Began)
            {
                // Raycast(光線の出る位置, 光線の向き)
                this.hit = Physics2D.Raycast(this.touch_point, Vector2.zero);
                if (this.hit)
                {
                    GameObject selectedObject = this.hit.collider.gameObject;
                    switch (selectedObject.name)
                    {
                        case "Scal":
                            selectedObject.SendMessage("ShowsUp");
                            break;
                        case "ScalJumpsOut":
                            selectedObject.SendMessage("JumpsOut");
                            break;
                    }
                }
            }
        }
    }
Beispiel #2
0
	bool IsValidTouch(Touch touch) {
		if ( touch.phase != TouchPhase.Began && touch.phase != TouchPhase.Moved ) 
			return false;
		Ray ray = Camera.main.ScreenPointToRay(touch.position);
		RaycastHit hit;
		return touchCollider.Raycast(ray, out hit, 100.0f);
	}
Beispiel #3
0
    // Update is called once per frame
    public void Update(Touch touch)
    {
        // Is Touch over UI
        int pointerID = touch.fingerId;
        if (EventSystem.current.IsPointerOverGameObject(pointerID))
        {
            return;
        }

        var phase = touch.phase;
        switch (phase)
        {
            case TouchPhase.Began:
                Began = true;
                break;
            case TouchPhase.Moved:
                Moved = true;
                break;
            case TouchPhase.Stationary:
                Stationary = true;
                break;
            case TouchPhase.Ended:
                Ended = true;
                break;
        }
    }
	public override void onTouchEnded( Touch touch, Vector2 touchPos, bool touchWasInsideTouchFrame )
	{
		base.onTouchEnded( touch, touchPos, touchWasInsideTouchFrame );
		
		if( onlyFireStartAndEndEvents && onActivationEnded != null )
			onActivationEnded( this );
	}
	// Touch handlers
	public override void onTouchBegan( Touch touch, Vector2 touchPos )
	{
		base.onTouchBegan( touch, touchPos );

		if( onlyFireStartAndEndEvents && onActivationStarted != null )
			onActivationStarted( this );
	}
    protected override void ForEachTouch(Touch touch, Vector2 guiTouchPos)
    {

        bool shouldLatchFinger = gui.HitTest(touch.position);

        if (shouldLatchFinger && (lastFingerId == -1 || lastFingerId != touch.fingerId)) {
            lastFingerId = touch.fingerId;

            // Tell other joysticks we've latched this finger
            for (int index = 0; index < joysticks.Length; index++) {
                if (joysticks[index] != this) {
                    joysticks[index].LatchedFinger (touch.fingerId);
                }
            }
        }
        if (lastFingerId == touch.fingerId) {
                // Change the location of the joystick graphic to match where the touch is
                gui.pixelInset = new Rect (
                    Mathf.Clamp (guiTouchPos.x, guiBoundary.xMin, guiBoundary.xMax),
                    Mathf.Clamp (guiTouchPos.y, guiBoundary.yMin, guiBoundary.yMax),
                    gui.pixelInset.width,
                    gui.pixelInset.height);

                // if the touch is over then reset the joystick to its default position
                if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled) {
                    ResetJoystick ();
                }
            }
    }
	void RegisterSpins()
	{
		if (Input.touchCount == 2)
		{
			touchOne = Input.GetTouch(0);
			touchTwo = Input.GetTouch(1);
			touchOnePrev = touchOne.position - touchOne.deltaPosition;
			touchTwoPrev = touchTwo.position - touchTwo.deltaPosition;
			currentAngle = Angle(touchOne.position, touchTwo.position);
			prevAngle = Angle(touchOnePrev, touchTwoPrev);
			deltaAngle = Mathf.DeltaAngle(currentAngle, prevAngle);
			if (Mathf.Abs(deltaAngle) > minAngle){
				spinInput = deltaAngle * (Mathf.PI / 2);
				spinning = true;
			}
			else {
				spinInput = 0;
				deltaAngle = 0;
				spinning = false;
			}
		}
		else {
			spinInput = 0;
		}
	}
Beispiel #8
0
    /**
    * Method:    Orbit
    * FullName:  Orbit
    * Access:    public
    * Qualifier:
    * @param   Touch touch
    * @return   void
    */
    void Orbit(Touch touch)
    {
        // rotates around the building

        x += touch.deltaPosition.x * xSpeed * 0.02f /* * distance*/;

        // rotates up and down (roof top)

        y -= touch.deltaPosition.y * ySpeed * 0.02f /* * distance*/;

        y = ClampAngle(y, yMinLimit, yMaxLimit);

        Quaternion rotation = Quaternion.Euler(y, x, 0);

        RaycastHit hit;

        if (Physics.Linecast(target.position, transform.position, out hit))

        {

              // distance -= hit.distance;

        }

        Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);

        Vector3 position = rotation * negDistance + target.position;

        transform.rotation = rotation;

        transform.position = position;
    }
    protected override void ForEachTouch(Touch touch, Vector2 guiTouchPos)
    {
        base.ForEachTouch(touch, guiTouchPos);

        if (lastFingerId == touch.fingerId)
        {
            // absolute position of touch relative to touchpad defines the input amount:
            Vector2 newAbsTouchPos = new Vector2((touch.position.x - touchZoneRect.center.x) / sensitivityRelativeX, (touch.position.y - touchZoneRect.center.y) / sensitivityRelativeY) * 2;

            Vector2 newPosition = Vector2.Lerp(position, newAbsTouchPos * sensitivity, Time.deltaTime * interpolateTime);

            // scale & clamp the touch position inside the allowed touch zone, between -1 and 1
            if (useX)
            {
                position.x = Mathf.Clamp(newPosition.x, -1, 1);
            }
            if (useY)
            {
                position.y = Mathf.Clamp(newPosition.y, -1, 1);
            }


            // if the touch is over then reset the joystick to its default position
            if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
            {
                ResetJoystick();
            }
        }
    }
 protected override void ForEachTouch(Touch touch, Vector2 guiTouchPos)
 {
     base.ForEachTouch(touch, guiTouchPos);
     if (this.lastFingerId != touch.fingerId)
     {
         return;
     }
     if (touch.phase == TouchPhase.Began)
     {
         this.touchStart = touch.position;
     }
     Vector2 a = new Vector2((touch.position.x - this.touchStart.x) / this.sensitivityRelativeX, (touch.position.y - this.touchStart.y) / this.sensitivityRelativeY);
     Vector2 vector = Vector2.Lerp(this.position, a * this.sensitivity * 2f, Time.deltaTime * this.interpolateTime);
     if (this.useX)
     {
         this.position.x = Mathf.Clamp(vector.x, -1f, 1f);
     }
     if (this.useY)
     {
         this.position.y = Mathf.Clamp(vector.y, -1f, 1f);
     }
     if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
     {
         base.ResetJoystick();
     }
 }
Beispiel #11
0
 /// <summary>
 /// Call when touch.phase = End
 /// </summary>
 /// <param name="touch"></param>
 public override void onTouchEnd(Touch touch)
 {
     base.onTouchEnd (touch);
     foreach (GameEvent e in event_on_touch) {
         LevelManager.OnGameEvent (e , this);
     }
 }
    void TouchPlacement()
    {
        //Raycast to find out where the building should be placed
        RaycastHit placement;
        //Finding mouse position when left mouse button is pressed
        touchPlace = Input.GetTouch(0);
        //Translating screen position of mouse to world position on the field.
        Ray touch = Camera.main.ScreenPointToRay(touchPlace.position);

        //If the click actually lands on the field it will fire the cannonball
        if (Physics.Raycast(touch, out placement))
        {
            //Finding how tall the building is to place it on the surface of the ground
            buildDimensions = buildingSub.GetComponent<Renderer>().bounds.size;
            yOffset = (buildDimensions.y/2) + placement.point.y;
            //Calculating height to have buildling resting on surface of ground
            surfacePlace = new Vector3(((int)(placement.point.x/10))*10, yOffset, ((int)(placement.point.z/10))*10);
            //Checking if the new building overlaps any other buildings; terminates if true
            spaceCheck = Physics.OverlapSphere(surfacePlace, buildDimensions.x/2);
            foreach(Collider other in spaceCheck)
            {
                GameObject otherBuilding = other.gameObject;
                if(otherBuilding.gameObject.CompareTag("Building"))
                {
                    return;
                }
            }
            //Placing building on surface
            building = Instantiate(buildingSub, surfacePlace, Quaternion.identity) as GameObject;
        }
    }
Beispiel #13
0
	// Update is called once per frame
	void Update () {
		touch = Input.GetTouch (0);
		
		// ゲーム中ではなく、タッチ直後であればtrueを返す。

		if (touch.phase == TouchPhase.Began) {
			
			result(Application.loadedLevelName);
			
		}


		if ( goTime >= 0f ) {
			goTime -= Time.deltaTime;
			return;
		}


		result(Application.loadedLevelName);



		
		
	}
Beispiel #14
0
    void MoveInputAt(Touch touch, int n)
    {
        Ray ray = InputCamera.ScreenPointToRay(touch.position);
        RaycastHit hit;
        //Handle Swipe
        if (Mathf.Abs(touch.position.x - SwipeInfos[n].StartPos.x) > comfortZone) { //Cant be swipe is deviate too much from a straith line
            SwipeInfos[n].canBeSwipe_Vertical = false;
            //Debug.Log("Swipe Cancelled by mouv : " + n);
        }
        if (Mathf.Abs(touch.position.y - SwipeInfos[n].StartPos.y) > comfortZone) { //Cant be swipe is deviate too much from a straith line
            SwipeInfos[n].canBeSwipe_Horizontal = false;
            //Debug.Log("Swipe Cancelled by mouv : " + n);
        }
        SwipeInfos[n].idleTime = 0;

        //check Button presses
        if (Physics.Raycast(ray, out hit, TouchInputMask)) {

            GameObject newRecipient = hit.collider.transform.gameObject;
            if (touchesTargets[n] != null && touchesTargets[n] == newRecipient) {
                return;//We are on the same target even though we moved, handle swipes here
            } else {
                RemoveInputFromButton(touch, n);
                newRecipient.SendMessage("FingerOn", n, SendMessageOptions.DontRequireReceiver);
                touchesTargets[n] = newRecipient;
            }

        }
    }
	// Update is called once per frame
	void Update () {

		if (InventoryFunctions.displayInventoryContents) {
			displayWardrobeContents = false;
		}

		if (displayWardrobeContents) { 

			// show the related tutorial message if it has not been shown before
			if (showTutorialFirstTimeOpened) {
				if (MostRecentGamePlaySettings.showTutorialMessages) {
					TutorialManager.tutorialMessageKeyword = "Wardrobe00";
					TutorialManager.showMessageIfNew = true;
				}
				showTutorialFirstTimeOpened = false;
			}

			// allow scrolling from other parts of the screen beside the scrollbar
			if (Input.touchCount > 0) {									
				
				myTouch = Input.touches [0];
				if (myTouch.phase == TouchPhase.Moved) {
					scrollPosition.y += myTouch.deltaPosition.y * 7;
				}
			} // end scroll on screen
		}

	} // end update
Beispiel #16
0
    void Update() {
        
        if (Input.touchCount <= 0) {
            ID = -1;
        }
        else if (ID == -1 && Input.touchCount > 0) {
            for (var i = 0; i < Input.touchCount; ++i) {
                Vector2 temp = new Vector2(Input.touches[i].position.x, Input.touches[i].position.y) - startPos;
                if (temp.magnitude < radius * canvas.scaleFactor) {
                    if (Input.touches[i].phase == TouchPhase.Began) {
                        ID = Input.touches[i].fingerId;
                        action = true;
                        TouchOnJoystick = Input.touches[i];
                        Debug.Log(TouchOnJoystick.fingerId);
                    }
                }
            }
        }

        for (var i = 0; i < Input.touchCount; ++i) {
            if (ID == Input.touches[i].fingerId && action) {
                FollowFinger(Input.touches[i].position);
            }
        }

        for (var i = 0; i < Input.touchCount; ++i) {
            if (ID == Input.touches[i].fingerId && action) {
                if(Input.touches[i].phase == TouchPhase.Canceled || Input.touches[i].phase == TouchPhase.Ended) {
                    action = false;
                    if (joystickImage) {
                        joystickImage.CrossFadeAlpha(0.2f, .1f, true);
                    }
                    transform.position = startPos;
                    ID = -1;
                }
            }
        }

        UpdateInput();

#if UNITY_EDITOR
        /*//Mouse
        if (Input.GetMouseButtonDown(0)) {
            if (Mathf.Abs(Input.mousePosition.x - startPos.x) < radius &&
                    Mathf.Abs(Input.mousePosition.y - startPos.y) < radius) {
                FollowFinger(Input.mousePosition);
                action = true;
            }
        }

        if(Input.GetMouseButton(0) && action) {
            FollowFinger(Input.mousePosition);
        }
        
        if(Input.GetMouseButtonUp(0)) {
            gameObject.transform.position = startPos;
            action = false;
        }*/
#endif
    }
	public override void onTouchMoved( Touch touch, Vector2 touchPos )
#endif
	{
		// dont fire this continously if we were asked to only fire start and end
		if( !onlyFireStartAndEndEvents && onTouchIsDown != null )
			onTouchIsDown( this );
	}
    private float startTime; //    Time when touch first occured

    #endregion Fields

    #region Methods

    //    Assign a new touch to track
    public void assignTouch(Touch touch)
    {
        myTouch = touch;
        free = false;

        processTouch ();
    }
Beispiel #19
0
 void OnTouch(Touch touch)
 {
     if (IsPlayer (touch)) {
         player.outsideMotion = body.velocity;
         //player.body.AddForce(body.velocity);
     }
 }
Beispiel #20
0
 void OnTouchEnd(Touch touch)
 {
     if (IsPlayer(touch)) {
         player.outsideMotion = Vector3.zero;
         player = null;
     }
 }
	public static Touch createTouchFromInput( UIMouseState mouseState, ref Vector2? lastMousePosition )
	{
		var self = new Touch();
		ValueType valueSelf = self;
		var type = typeof( Touch );
		
		var currentMousePosition = new Vector2( Input.mousePosition.x, Input.mousePosition.y );
		
		// if we have a lastMousePosition use it to get a delta
		if( lastMousePosition.HasValue )
			type.GetField( "m_PositionDelta", BindingFlags.Instance | BindingFlags.NonPublic ).SetValue( valueSelf, currentMousePosition - lastMousePosition );
		
		if( mouseState == UIMouseState.DownThisFrame ) // equivalent to touchBegan
		{
			type.GetField( "m_Phase", BindingFlags.Instance | BindingFlags.NonPublic ).SetValue( valueSelf, TouchPhase.Began );
			lastMousePosition = Input.mousePosition;
		}
		else if( mouseState == UIMouseState.UpThisFrame ) // equivalent to touchEnded
		{
			type.GetField( "m_Phase", BindingFlags.Instance | BindingFlags.NonPublic ).SetValue( valueSelf, TouchPhase.Ended );
			lastMousePosition = null;
		}
		else // UIMouseState.HeldDown - equivalent to touchMoved/Stationary
		{
			type.GetField( "m_Phase", BindingFlags.Instance | BindingFlags.NonPublic ).SetValue( valueSelf, TouchPhase.Moved );
			lastMousePosition = Input.mousePosition;
		}
		
		type.GetField( "m_Position", BindingFlags.Instance | BindingFlags.NonPublic ).SetValue( valueSelf, currentMousePosition );
		
		return (Touch)valueSelf;
	}
Beispiel #22
0
        protected PointerEventData GetTouchPointerEventData(Touch input, out bool pressed, out bool released)
        {
            PointerEventData pointerData;
            var created = GetPointerData(input.fingerId, out pointerData, true);

            pointerData.Reset();

            pressed = created || (input.phase == TouchPhase.Began);
            released = (input.phase == TouchPhase.Canceled) || (input.phase == TouchPhase.Ended);

            if (created)
                pointerData.position = input.position;

            if (pressed)
                pointerData.delta = Vector2.zero;
            else
                pointerData.delta = input.position - pointerData.position;

            pointerData.position = input.position;

            pointerData.button = PointerEventData.InputButton.Left;

            eventSystem.RaycastAll(pointerData, m_RaycastResultCache);

            var raycast = FindFirstRaycast(m_RaycastResultCache);
            pointerData.pointerCurrentRaycast = raycast;
            m_RaycastResultCache.Clear();
            return pointerData;
        }
    protected override void ForEachTouch(Touch touch, Vector2 guiTouchPos)
    {
        base.ForEachTouch(touch, guiTouchPos);

        if (lastFingerId != touch.fingerId)
            return;
        // position of touch relative to touch start position defines the input amount:
        if (touch.phase == TouchPhase.Began)
        {
            touchStart = touch.position;
        }
        Vector2 newRelativeTouchPos = new Vector2((touch.position.x - touchStart.x) / sensitivityRelativeX, (touch.position.y - touchStart.y) / sensitivityRelativeY);

        Vector2 newPosition = Vector2.Lerp(position, newRelativeTouchPos * sensitivity * 2, Time.deltaTime * interpolateTime);

        // scale & clamp the touch position inside the allowed touch zone, between -1 and 1
        if (useX)
        {
            position.x = Mathf.Clamp(newPosition.x, -1, 1);
        }
        if (useY)
        {
            position.y = Mathf.Clamp(newPosition.y, -1, 1);
        }

        // if the touch is over then reset the joystick to its default position
        if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
        {
            ResetJoystick();
        }
    }
Beispiel #24
0
 protected override void ForEachTouch(Touch touch, Vector2 guiTouchPos)
 {
     base.ForEachTouch(touch, guiTouchPos);
     if (this.lastFingerId != touch.fingerId)
     {
         return;
     }
     if (touch.phase == TouchPhase.Began)
     {
         this.lastTouchPos = touch.position;
         this.touchDelta = Vector2.zero;
     }
     this.touchDelta = Vector2.Lerp(this.touchDelta, (this.lastTouchPos - touch.position) / this.swipeScale, Time.deltaTime * this.interpolateTime);
     if (touch.deltaTime > 0f)
     {
         if (this.useX)
         {
             float x = this.touchDelta.x * this.sensitivity;
             this.position.x = x;
         }
         if (this.useY)
         {
             float y = this.touchDelta.y * this.sensitivity;
             this.position.y = y;
         }
     }
     this.lastTouchPos = touch.position;
     this.lastTouchPos = touch.position;
     if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
     {
         base.ResetJoystick();
     }
 }
Beispiel #25
0
 public InputCommands(Keyboard keyboard, Mouse mouse, Touch touch, GamePad gamePad)
 {
     this.keyboard = keyboard;
     this.mouse = mouse;
     this.touch = touch;
     this.gamePad = gamePad;
 }
Beispiel #26
0
    void TouchShoot()
    {
        touch = Input.GetTouch (0);
        //Raycast to find out where the cannonball should be fired towards
        RaycastHit shothit;
        //Finding mouse position when left mouse button is pressed
        shot = touch.position;
        //Translating screen position of mouse to world position on the field.
        Ray mouseClick = Camera.main.ScreenPointToRay(shot);
        //Final vector for firing cannonball
        Vector3 shotdirection;

        //If the click actually lands on the field it will fire the cannonball
        if (Physics.Raycast(mouseClick, out shothit, Mathf.Infinity, layerMask))
        {
            if (shothit.collider.CompareTag ("Surface") || shothit.collider.CompareTag ("Surface"))
            {
                //Creating cannonball in front of cannon barrel
                reload = Instantiate(cannonball, shotorigin.position, shotorigin.rotation) as Rigidbody;
                //Calculating final shot vector by taking position of mouse and subtracting position of cannon
                shotdirection = shothit.point - reload.transform.position;
                shotdirection.Normalize ();
                //Applying force to cannonball along the vector
                reload.AddForce(shotdirection * shotspeed);
                //Play cannon animation
                GetComponent<Animation>().Play("Cannon_Fire");
            }

        }
    }
	void Update ()
    {
      
        if (Input.touchCount > 0)
        {
            myTouch = Input.GetTouch(0);
            myFIngerID = myTouch.fingerId;
        }

        else
        {
            iWasTouched = false;
            hasMoved = false;
        }

        if (EventSystem.current.IsPointerOverGameObject(myFIngerID) && Input.touchCount > 0)
        {
          
            iWasTouched = true;
          
            return;
        }

        gameObject.transform.GetChild(0).GetComponent<Text>().text = iWasTouched.ToString();

        if (iWasTouched == true && myTouch.phase == TouchPhase.Moved)
        {
            hasMoved = true;
            gameObject.transform.position = myTouch.position;

        }

    }
    private void DragObject(Touch touch)
    {
        //Gets the ray at position where the screen is touched
        Ray ray = Camera.main.ScreenPointToRay(touch.position);

        //Gets the position of ray along plane
        float dist = 0.0f;

        //Intersects ray with the plane. Sets dist to distance along the ray where intersects
        _TargetPlane.Raycast(ray, out dist);

        //Returns point dist along the ray.
        Vector3 planePoint = ray.GetPoint(dist);

        if (touch.phase == TouchPhase.Began)
        {
            // If finger touch began
            _LastPlanePoint = planePoint;
        } else if (touch.phase == TouchPhase.Moved)
        {
            // Else, we are moving
            _VegasObject.transform.position += planePoint - _LastPlanePoint;
            _LastPlanePoint = planePoint;
        }
    }
    private void TestForTouchOrSwipeGesture(Touch touch)
    {
        Vector2 lastPosition = touch.position;
        float distance = Vector2.Distance(lastPosition, touchStartPosition);

        if (distance > minimumSwipeDistanceInPixels)
        {
            float dy = lastPosition.y - touchStartPosition.y;
            float dx = lastPosition.x - touchStartPosition.x;

            float angle = Mathf.Rad2Deg * Mathf.Atan2(dx, dy);

            angle = (360 + angle - 45) % 360;

            if (angle < 90)
                OnSwipeDetectedRaise(Swipe.Right);
            else if (angle < 180)
                OnSwipeDetectedRaise(Swipe.Down);
            else if (angle < 270)
                OnSwipeDetectedRaise(Swipe.Left);
            else
                OnSwipeDetectedRaise(Swipe.Up);
        }
        else
        {
            OnTouchDetectedRaise(touch);
        }
    }
Beispiel #30
0
    private void Update() {
        
        if(Interactable) {
            foreach(Touch touch in Input.touches) {
                if(rectTransform.rect.Contains((Vector3) touch.position - rectTransform.position) && touch.phase == TouchPhase.Began) {
                    followTouch = touch;
                    OnPointerDown();
                    
                }
            }

            foreach (Touch touch in Input.touches) {
                if (followTouch.fingerId == touch.fingerId && rectTransform.rect.Contains((Vector3)touch.position - rectTransform.position)) {
                    if (OnHold != null)
                        OnHold.Invoke();
                }
            }

            foreach (Touch touch in Input.touches) {
                if(followTouch.fingerId == touch.fingerId && 
                    (touch.phase == TouchPhase.Ended 
                    || touch.phase == TouchPhase.Canceled 
                    || !rectTransform.rect.Contains((Vector3) touch.position - rectTransform.position))) {
                    OnPointerUp();
                }
            }
        }

    }
Beispiel #31
0
        private void PlayerUpdate()
        {
            //Set current posistion on grid
            currentPosition = Global.RoundVector3(transform.position);
            //Set current chunk
            int px = (int)currentPosition.x, pz = (int)currentPosition.z;
            int cx = 0, cz = 0;

            while (px > Global.maxChunkSize)
            {
                px -= Global.maxChunkSize;
                cx++;
            }
            while (px < -Global.maxChunkSize)
            {
                px += Global.maxChunkSize;
                cx--;
            }
            while (pz > Global.maxChunkSize)
            {
                pz -= Global.maxChunkSize;
                cz++;
            }
            while (pz < -Global.maxChunkSize)
            {
                pz += Global.maxChunkSize;
                cz--;
            }
            currentChunk = new Vector2(cx, cz);

            //Mouse cursor state
            if (lockMouse)
            {
                Cursor.lockState = CursorLockMode.Locked;
            }
            else
            {
                Cursor.lockState = CursorLockMode.None;
            }

            if (Input.GetKey(KeyCode.LeftShift) && Input.GetKeyDown(KeyCode.G))
            {
                if (lockMouse)
                {
                    lockMouse = false;
                }
                else
                {
                    lockMouse = true;
                }
            }

            //Game mode dependant stuff
            //==========================
            //Platform NO/G
            if (Global.GameType == 0)
            {
            }
            //Platform WITH/G
            if (Global.GameType == 1)
            {
            }
            //2.5d HYPER
            if (Global.GameType == 2)
            {
                int tDir = 0;// temp turn direction

#if UNITY_IOS || UNITY_ANDROID || UNITY_WP8 || UNITY_IPHONE
                currentPosition = Global.RoundVector3(transform.position);
                if (currentPosition == tempPos && moveSpeed > 0)
                {
                    moveSpeed = 0;
                }

                if (Input.touchCount > 0)
                {
                    Touch   touch1 = Input.touches[0];
                    int     width  = Screen.width;
                    int     height = Screen.height;
                    Vector2 tPos   = new Vector2(Mathf.InverseLerp(width, 0, touch1.position.x), Mathf.InverseLerp(height, 0, touch1.position.y));
                    //Debug.Log("tPos: " + tPos);
                    if (tPos.y > 0.8f && tPos.x > 0.2f && tPos.x < 0.8f)
                    {
                        // moveSpeed += Time.deltaTime * accelleration;
                        moveSpeed = accelleration;
                    }
                    else if (tPos.y < 0.2f && tPos.x > 0.2f && tPos.x < 0.8f)
                    {
                        // moveSpeed -= Time.deltaTime * accelleration;
                        moveSpeed = accelleration;
                    }
                    switch (touch1.phase)
                    {
                    case TouchPhase.Began:
                        if (tPos.x > 0.8f)
                        {
                            tDir = -90;
                        }
                        if (tPos.x < 0.2f)
                        {
                            tDir = 90;
                        }
                        if (tPos.y < 0.8f && tPos.y > 0.2f && tPos.x > 0.2f && tPos.x < 0.8f)
                        {
                            Interact(true);
                        }

                        if (tPos.y > 0.8f && tPos.x > 0.2f && tPos.x < 0.8f)
                        {
                            tempPos = Global.RoundVector3(currentPosition + transform.TransformDirection(Vector3.forward).normalized);
                        }
                        if (tPos.y < 0.2f && tPos.x > 0.2f && tPos.x < 0.8f)
                        {
                            tempPos = Global.RoundVector3(currentPosition + transform.TransformDirection(Vector3.forward).normalized);
                        }

                        break;
                    }
                }
                transform.position = Vector3.MoveTowards(transform.position, tempPos, Time.deltaTime * accelleration);
#elif UNITY_STANDALONE || UNITY_WEBPLAYER
                if (Input.GetButtonDown("Fire1"))
                {
                    Interact();
                }
                moveSpeed += Input.GetAxis("Vertical") * Time.deltaTime * accelleration;

                if (Input.GetButtonDown("Left"))
                {
                    tDir = -90;
                }
                if (Input.GetButtonDown("Right"))
                {
                    tDir = 90;
                }

                //Movement
                targetPosition = Global.RoundVector3(transform.position) + transform.TransformDirection(Vector3.forward);
                if (moveSpeed > maxMoveSpeed)
                {
                    moveSpeed = maxMoveSpeed;
                }
                GB2DMovement.MoveUpdate(transform, moveSpeed, targetPosition, true);
#endif



                targetRotation = GB2DMovement.TurnUpdate(targetRotation, transform, tDir, turnSpeed);
            }
            //2.5d WOLF
            if (Global.GameType == 3)
            {
                if (Input.GetButton("Fire1") && iDelayTime >= interactDelay)
                {
                    Interact();
                    iDelayTime = 0f;
                }
                if (lockMouse)
                {
                    GB3DMovement.MoveUpdate(transform, maxMoveSpeed, turnSpeed);
                }
            }
            //3d
            if (Global.GameType == 4)
            {
            }
            //flight
            if (Global.GameType == 5)
            {
            }
        }
Beispiel #32
0
    void TryGetActiveObject(Touch touch)
    {
        Ray        ray = Camera.main.ScreenPointToRay(touch.position);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, Mathf.Infinity))
        {
            //If the raycast has hit a boat
            if (hit.transform.tag == "Boat")
            {
                BoatComponent[] boats = hit.transform.parent.GetComponentsInChildren <BoatComponent>();
                //If the boat is already on the grid
                if (boats[0].m_bOnGrid)
                {
                    //Get the parent of the boat component
                    m_activeDragObject = hit.transform.parent.gameObject;

                    //Loop through each boat component
                    foreach (BoatComponent boat in boats)
                    {
                        //Get the grid cell the boat is on
                        GridCell bCell = GridCellManager.instance.GetGridCellByPosition(boat.transform.position);
                        //If this is a valid cell (i.e on the grid)
                        if (bCell != null)
                        {
                            //Add the cell to the last active cell list
                            m_lastActiveCells.Add(bCell);
                        }
                    }
                }
                //If the boat isn't already on the grid
                else
                {
                    //Instantiate a copy of the "boat spawner"
                    //m_activeDragObject = Instantiate(hit.transform.parent.gameObject, m_gridPlane.transform.parent);

                    m_activeDragObject = hit.transform.parent.gameObject;

                    //Set the last spawn prefab to this "boat spawner"
                    m_lastSpawnPrefab = hit.transform.parent.gameObject;
                    //Set the spawner to not be active
                    //m_lastSpawnPrefab.SetActive(false);
                }

                //If we don't have a last active object
                if (m_lastActiveObject == null)
                {
                    //Set the last active object to this new object
                    m_lastActiveObject = m_activeDragObject;
                    //Activate it's rotate canvas
                    m_lastActiveObject.transform.Find("RotateButtonCanvas").gameObject.SetActive(true);
                }
                else
                {
                    //Clicked on a different object
                    if (m_activeDragObject != m_lastActiveObject)
                    {
                        m_lastActiveObject.transform.Find("RotateButtonCanvas").gameObject.SetActive(false);
                        m_lastActiveObject = m_activeDragObject;
                        m_lastActiveObject.transform.Find("RotateButtonCanvas").gameObject.SetActive(true);
                    }
                }
            }
        }
    }
Beispiel #33
0
    void HandleTouchEnded(Touch touch)
    {
        if (m_activeDragObject != null)
        {
            //Get current cell finger is on
            GridCell cell = GetCellFromRay(touch, m_cellLayer);

            //Store the last position
            Vector3 lastPos;

            BoatComponent[] boats = m_activeDragObject.GetComponentsInChildren <BoatComponent>();

            //If this is a valid cell
            if (cell != null)
            {
                //Store last position
                lastPos = m_activeDragObject.transform.position;

                //Move boat to new position
                m_activeDragObject.transform.position = cell.transform.position;

                bool allCellsFree = CheckIfFree(boats);

                //If all the cells are free
                if (allCellsFree)
                {
                    //Set the new position of the object
                    m_activeDragObject.transform.position = cell.transform.position;

                    //Make sure they're set as now on the grid
                    foreach (BoatComponent b in boats)
                    {
                        b.m_bOnGrid = true;
                    }

                    if (m_lastActiveCells.Count > 0)
                    {
                        if (m_lastActiveCells[0] != null)
                        {
                            //If we have moved onto a new grid cell
                            if (cell.gameObject != m_lastActiveCells[0].gameObject)
                            {
                                //Set the old cells to be free
                                foreach (GridCell c in m_lastActiveCells)
                                {
                                    c.m_bIsFree     = true;
                                    c.m_blockingObj = null;
                                }
                            }
                        }
                    }

                    //Clear the last active cells list
                    m_lastActiveCells.Clear();
                    m_lastActiveCells.Capacity = 0;

                    //Loop through the boats
                    foreach (BoatComponent b in boats)
                    {
                        //Get every cell the boat is touching
                        GridCell bCell = GridCellManager.instance.GetGridCellByPosition(b.transform.position);
                        //Add it to the last active cell list
                        m_lastActiveCells.Add(bCell);
                        bCell.m_bIsFree     = false;
                        bCell.m_blockingObj = b.transform.parent.gameObject;
                    }
                }
                //If the cells aren't free then move back to original position
                else
                {
                    m_activeDragObject.transform.position = lastPos;
                }
            }
            //If we haven't finished the touch on the grid
            else
            {
                Vector3 originalPos = m_activeDragObject.transform.GetChild(0).GetComponent <BoatComponent>().m_originalPosition;
                m_activeDragObject.transform.localPosition = originalPos;
                //Quaternion originalRot = m_activeDragObject.transform.GetChild(0).GetComponent<BoatComponent>().m_originalRotation;

                //m_activeDragObject.transform.rotation = originalRot;

                m_lastActiveObject.transform.Find("RotateButtonCanvas").gameObject.SetActive(false);
                m_lastActiveObject = null;
            }

            foreach (BoatComponent b in boats)
            {
                GridCell bCell = GridCellManager.instance.GetGridCellByPosition(b.transform.position);
                bCell.m_bIsFree     = false;
                bCell.m_blockingObj = b.transform.parent.gameObject;
            }

            m_lastActiveCells.Clear();

            //if (m_activeDragObject.GetComponentInChildren<BoatComponent>().m_bOnGrid == false)
            //{
            //    Destroy(m_activeDragObject);
            //}
        }

        m_activeDragObject = null;
    }
Beispiel #34
0
    /// <summary>
    /// Checks the user input and moves the tetromino down
    /// </summary>
    private void CheckUserInput()
    {
        // This method checks the keys that the player can press to manipulate the position of the tetromino
        // The options here will be left, right, up and down
        // Left and right will move the tetromino 1 unit to the left or right
        // Down will move the tetromino 1 unit down
        // Up will rotate the tetromino

#if UNITY_IOS
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);

            if (touch.phase == TouchPhase.Began)
            {
                previousUnitPosition = new Vector2(touch.position.x, touch.position.y);
            }
            else if (touch.phase == TouchPhase.Moved)
            {
                Vector2 touchDeltaPosition = touch.deltaPosition;
                direction = touchDeltaPosition.normalized;

                if (Mathf.Abs(touch.position.x - previousUnitPosition.x) >= Game.Instance.TouchSensitivityHorizontal && direction.x < 0 && touch.deltaPosition.y > -10 && touch.deltaPosition.y < 10)
                {
                    // Move Left
                    MoveLeft();
                    previousUnitPosition = touch.position;
                    moved = true;
                }
                else if (Mathf.Abs(touch.position.x - previousUnitPosition.x) >= Game.Instance.TouchSensitivityHorizontal && direction.x > 0 && touch.deltaPosition.y > -10 && touch.deltaPosition.y < 10)
                {
                    // Move Right
                    MoveRight();
                    previousUnitPosition = touch.position;
                    moved = true;
                }
                else if (Mathf.Abs(touch.position.y - previousUnitPosition.y) >= Game.Instance.TouchSensitivityVertical && direction.y < 0 && touch.deltaPosition.x > -10 && touch.deltaPosition.x < 10)
                {
                    // Move Down
                    MoveDown();
                    previousUnitPosition = touch.position;
                    moved = true;
                }
            }
            else if (touch.phase == TouchPhase.Ended)
            {
                if (!moved && touch.position.x > Screen.width / 4)
                {
                    Rotate();
                }

                moved = false;
            }
        }

        if (Time.time - fallTimer >= Game.Instance.FallSpeed)
        {
            MoveDown();
        }
#else
        SavedControl moveLeft     = Game.Instance.Controls.FirstOrDefault(x => x.ControlType == SavedControl.Type.MoveLeft);
        SavedControl moveRight    = Game.Instance.Controls.FirstOrDefault(x => x.ControlType == SavedControl.Type.MoveRight);
        SavedControl moveDown     = Game.Instance.Controls.FirstOrDefault(x => x.ControlType == SavedControl.Type.MoveDown);
        SavedControl rotate       = Game.Instance.Controls.FirstOrDefault(x => x.ControlType == SavedControl.Type.Rotate);
        SavedControl moveToBottom = Game.Instance.Controls.FirstOrDefault(x => x.ControlType == SavedControl.Type.MoveToBottom);
        SavedControl save         = Game.Instance.Controls.FirstOrDefault(x => x.ControlType == SavedControl.Type.SaveTetromino);

        if (Input.GetKeyUp(moveRight.Key) || Input.GetKeyUp(moveLeft.Key))
        {
            movedImmediateHorizontal      = false;
            horizontalTimer               = 0;
            buttonDownWaitTimerHorizontal = 0;
        }

        if (Input.GetKeyUp(moveDown.Key))
        {
            movedImmediateVertical      = false;
            verticalTimer               = 0;
            buttonDownWaitTimerVertical = 0;
        }

        if (Input.GetKey(moveRight.Key))
        {
            MoveRight();
        }

        if (Input.GetKey(moveLeft.Key))
        {
            MoveLeft();
        }

        if (Input.GetKeyDown(rotate.Key))
        {
            Rotate();
        }

        if (Input.GetKey(moveDown.Key) || Time.time - fallTimer >= Game.Instance.FallSpeed)
        {
            MoveDown();
        }

        if (Input.GetKeyDown(moveToBottom.Key))
        {
            MoveToBottom();
        }
#endif
    }
Beispiel #35
0
        private void Update()
        {
            //If it's not the player's turn, exit the function.
            if (!GameManager.instance.playersTurn)
            {
                return;
            }

            int horizontal = 0;     //Used to store the horizontal move direction.
            int vertical   = 0;     //Used to store the vertical move direction.

            //Check if we are running either in the Unity editor or in a standalone build.
#if UNITY_STANDALONE || UNITY_WEBPLAYER
            //Get input from the input manager, round it to an integer and store in horizontal to set x axis move direction
            horizontal = (int)(Input.GetAxisRaw("Horizontal"));

            //Get input from the input manager, round it to an integer and store in vertical to set y axis move direction
            vertical = (int)(Input.GetAxisRaw("Vertical"));

            //Check if moving horizontally, if so set vertical to zero.
            if (horizontal != 0)
            {
                vertical = 0;
            }
            //Check if we are running on iOS, Android, Windows Phone 8 or Unity iPhone
#elif UNITY_IOS || UNITY_ANDROID || UNITY_WP8 || UNITY_IPHONE
            //Check if Input has registered more than zero touches
            if (Input.touchCount > 0)
            {
                //Store the first touch detected.
                Touch myTouch = Input.touches[0];

                //Check if the phase of that touch equals Began
                if (myTouch.phase == TouchPhase.Began)
                {
                    //If so, set touchOrigin to the position of that touch
                    touchOrigin = myTouch.position;
                }

                //If the touch phase is not Began, and instead is equal to Ended and the x of touchOrigin is greater or equal to zero:
                else if (myTouch.phase == TouchPhase.Ended && touchOrigin.x >= 0)
                {
                    //Set touchEnd to equal the position of this touch
                    Vector2 touchEnd = myTouch.position;

                    //Calculate the difference between the beginning and end of the touch on the x axis.
                    float x = touchEnd.x - touchOrigin.x;

                    //Calculate the difference between the beginning and end of the touch on the y axis.
                    float y = touchEnd.y - touchOrigin.y;

                    //Set touchOrigin.x to -1 so that our else if statement will evaluate false and not repeat immediately.
                    touchOrigin.x = -1;

                    //Check if the difference along the x axis is greater than the difference along the y axis.
                    if (Mathf.Abs(x) > Mathf.Abs(y))
                    {
                        //If x is greater than zero, set horizontal to 1, otherwise set it to -1
                        horizontal = x > 0 ? 1 : -1;
                    }
                    else
                    {
                        //If y is greater than zero, set horizontal to 1, otherwise set it to -1
                        vertical = y > 0 ? 1 : -1;
                    }
                }
            }
#endif //End of mobile platform dependendent compilation section started above with #elif
            //Check if we have a non-zero value for horizontal or vertical
            if (horizontal != 0 || vertical != 0)
            {
                //Call AttemptMove passing in the generic parameter Wall, since that is what Player may interact with if they encounter one (by attacking it)
                //Pass in horizontal and vertical as parameters to specify the direction to move Player in.
                AttemptMove <Wall>(horizontal, vertical);
            }
        }
    void Update()
    {
        if (isOnPc != true)
        {
            if (Input.GetMouseButtonDown(0))
            {
                Touch touch = Input.GetTouch(0);
                ray = Camera.main.ScreenPointToRay(touch.position);


                //layerMask = ~layerMask;
                if (Physics.Raycast(ray, out hit, 100.0f))
                {
                    Debug.Log(hit.collider.name);
                    Debug.Log(EventSystem.current.IsPointerOverGameObject());
                    if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
                    {
                        return;
                    }

                    else if (!hit.collider.CompareTag("Node"))
                    {
                        nodeUI.HideBuildUI();
                        nodeUI.ResetConfirmation();
                        Destroy(Node.ghostContainer);
                        Node.ghostContainer = null;
                        Node.haveGhost      = false;
                        nodeUI.HideUpDemUI();
                        //test.text = Input.GetTouch(0).position.ToString();
                    }
                }

                Debug.DrawLine(ray.origin, hit.point, Color.red, 5.0f);
            }
        }
        else
        {
            if (Input.GetMouseButtonDown(0))
            {
                ray = Camera.main.ScreenPointToRay(Input.mousePosition);


                //layerMask = ~layerMask;
                if (Physics.Raycast(ray, out hit, 100.0f))
                {
                    Debug.Log(hit.collider.name);
                    Debug.Log(EventSystem.current.IsPointerOverGameObject());
                    if (EventSystem.current.IsPointerOverGameObject())
                    {
                        return;
                    }

                    else if (!hit.collider.CompareTag("Node"))
                    {
                        nodeUI.HideBuildUI();
                        nodeUI.ResetConfirmation();
                        Destroy(Node.ghostContainer);
                        Node.ghostContainer = null;
                        Node.haveGhost      = false;
                        nodeUI.HideUpDemUI();
                        //test.text = Input.GetTouch(0).position.ToString();
                    }
                }

                Debug.DrawLine(ray.origin, hit.point, Color.red, 5.0f);
            }
        }
    }
Beispiel #37
0
    void Update()
    {
        if (Input.touchCount == 2)
        {
            ScrollStart = false;

            Touch touchZero = Input.GetTouch(0);
            Touch touchOne  = Input.GetTouch(1);

            Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
            Vector2 touchOnePrevPos  = touchOne.position - touchOne.deltaPosition;

            float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
            float touchDeltaMag     = (touchZero.position - touchOne.position).magnitude;

            float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;

            if (camera.orthographic)
            {
                camera.orthographicSize += deltaMagnitudeDiff * orthoZoomSpeed;

                // 平行投影サイズが決して 0 未満にならないように気を付けてください
                camera.orthographicSize = Mathf.Max(camera.orthographicSize, 6f);
                camera.orthographicSize = Mathf.Min(camera.orthographicSize, 20f);
            }
            else
            {
                // そうでない場合は、タッチ間の距離の変化に基づいて有効視野を変更します
                camera.fieldOfView += deltaMagnitudeDiff * perspectiveZoomSpeed;

                // 有効視野を 0 から 180 の間に固定するように気を付けてください
                camera.fieldOfView = Mathf.Clamp(camera.fieldOfView, 0.1f, 179.9f);
            }
        }
        else if (Input.touchCount == 1)
        {
            if (!ScrollStart)
            {
                ScrollStart    = true;
                ScrollStartPos = Input.GetTouch(0).position.x;
            }
            ScrollAmount = (ScrollStartPos - Input.GetTouch(0).position.x) * 0.07f;
            if (ScrollAmount + RetentionPos <= TowerDistance * -1)
            {
                camera.transform.position = new Vector3(TowerDistance * -1, camera.transform.position.y, camera.transform.position.z);
            }
            else if (ScrollAmount + RetentionPos >= TowerDistance)
            {
                camera.transform.position = new Vector3(TowerDistance, camera.transform.position.y, camera.transform.position.z);
            }
            else
            {
                camera.transform.position = new Vector3(ScrollAmount + RetentionPos, camera.transform.position.y, camera.transform.position.z);
            }
        }
        else
        {
            ScrollStart = false;
        }
        if (!ScrollStart)
        {
            RetentionPos = camera.transform.position.x;
        }
        if (Reset_Poses)
        {
            Reset_Poses               = false;
            ScrollStartPos            = 0f;
            RetentionPos              = 0f;
            ScrollAmount              = 0f;
            camera.transform.position = new Vector3(0, camera.transform.position.y, camera.transform.position.z);
        }
        _Debug1     = camera.orthographicSize;
        _Text1.text = _Debug1.ToString();
        _Debug2     = camera.transform.position.x;
        _Text2.text = _Debug2.ToString();

        float _Scale = 20f / camera.orthographicSize;

        _BG.GetComponent <RectTransform>().localScale = new Vector3(_Scale, _Scale, _Scale);

        /*
         * Vector3 _BGPos = _BG.transform.position;
         * _BGPos.x = _Debug2 * 0.5f;
         * _BG.transform.position = _BGPos;
         * //*/
        /*
         * Vector3 _BGPos = _BG.GetComponent<RectTransform>().anchoredPosition3D;
         * _BGPos.x = _Debug2 * -100;
         * _BG.GetComponent<RectTransform>().anchoredPosition3D = _BGPos;
         * //*/
        /*
         * Vector3 _BGPos = _BG.transform.position;
         * _BGPos.x = _Debug2;
         * _BG.transform.localPosition = _BGPos;
         * //*/

        _BG.transform.position = __Pos;
    }
Beispiel #38
0
        void GetPlayerInput()
        {
            moveVector = Vector3.zero;

            // Check Mouse Wheel Input prior to Shift Key so we can apply multiplier on Shift for Scrolling
            mouseWheel = Input.GetAxis("Mouse ScrollWheel");

            float touchCount = Input.touchCount;

            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift) || touchCount > 0)
            {
                mouseWheel *= 10;

                if (Input.GetKeyDown(KeyCode.I))
                {
                    CameraMode = CameraModes.Isometric;
                }

                if (Input.GetKeyDown(KeyCode.F))
                {
                    CameraMode = CameraModes.Follow;
                }

                if (Input.GetKeyDown(KeyCode.S))
                {
                    MovementSmoothing = !MovementSmoothing;
                }


                // Check for right mouse button to change camera follow and elevation angle
                if (Input.GetMouseButton(1))
                {
                    mouseY = Input.GetAxis("Mouse Y");
                    mouseX = Input.GetAxis("Mouse X");

                    if (mouseY > 0.01f || mouseY < -0.01f)
                    {
                        ElevationAngle -= mouseY * MoveSensitivity;
                        // Limit Elevation angle between min & max values.
                        ElevationAngle = Mathf.Clamp(ElevationAngle, MinElevationAngle, MaxElevationAngle);
                    }

                    if (mouseX > 0.01f || mouseX < -0.01f)
                    {
                        OrbitalAngle += mouseX * MoveSensitivity;
                        if (OrbitalAngle > 360)
                        {
                            OrbitalAngle -= 360;
                        }
                        if (OrbitalAngle < 0)
                        {
                            OrbitalAngle += 360;
                        }
                    }
                }

                // Get Input from Mobile Device
                if (touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)
                {
                    Vector2 deltaPosition = Input.GetTouch(0).deltaPosition;

                    // Handle elevation changes
                    if (deltaPosition.y > 0.01f || deltaPosition.y < -0.01f)
                    {
                        ElevationAngle -= deltaPosition.y * 0.1f;
                        // Limit Elevation angle between min & max values.
                        ElevationAngle = Mathf.Clamp(ElevationAngle, MinElevationAngle, MaxElevationAngle);
                    }


                    // Handle left & right
                    if (deltaPosition.x > 0.01f || deltaPosition.x < -0.01f)
                    {
                        OrbitalAngle += deltaPosition.x * 0.1f;
                        if (OrbitalAngle > 360)
                        {
                            OrbitalAngle -= 360;
                        }
                        if (OrbitalAngle < 0)
                        {
                            OrbitalAngle += 360;
                        }
                    }
                }

                // Check for left mouse button to select a new CameraTarget or to reset Follow position
                if (Input.GetMouseButton(0))
                {
                    Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                    RaycastHit hit;

                    if (Physics.Raycast(ray, out hit, 300, 1 << 10 | 1 << 11 | 1 << 12 | 1 << 14))
                    {
                        if (hit.transform == CameraTarget)
                        {
                            // reset Follow Position
                            OrbitalAngle = 0;
                        }
                        else
                        {
                            CameraTarget      = hit.transform;
                            OrbitalAngle      = 0;
                            MovementSmoothing = previousSmoothing;
                        }
                    }
                }


                if (Input.GetMouseButton(2))
                {
                    if (dummyTarget == null)
                    {
                        // We need a Dummy Target to anchor the Camera
                        dummyTarget          = new GameObject("Camera Target").transform;
                        dummyTarget.position = CameraTarget.position;
                        dummyTarget.rotation = CameraTarget.rotation;
                        CameraTarget         = dummyTarget;
                        previousSmoothing    = MovementSmoothing;
                        MovementSmoothing    = false;
                    }
                    else if (dummyTarget != CameraTarget)
                    {
                        // Move DummyTarget to CameraTarget
                        dummyTarget.position = CameraTarget.position;
                        dummyTarget.rotation = CameraTarget.rotation;
                        CameraTarget         = dummyTarget;
                        previousSmoothing    = MovementSmoothing;
                        MovementSmoothing    = false;
                    }


                    mouseY = Input.GetAxis("Mouse Y");
                    mouseX = Input.GetAxis("Mouse X");

                    moveVector = cameraTransform.TransformDirection(mouseX, mouseY, 0);

                    dummyTarget.Translate(-moveVector, Space.World);
                }
            }

            // Check Pinching to Zoom in - out on Mobile device
            if (touchCount == 2)
            {
                Touch touch0 = Input.GetTouch(0);
                Touch touch1 = Input.GetTouch(1);

                Vector2 touch0PrevPos = touch0.position - touch0.deltaPosition;
                Vector2 touch1PrevPos = touch1.position - touch1.deltaPosition;

                float prevTouchDelta = (touch0PrevPos - touch1PrevPos).magnitude;
                float touchDelta     = (touch0.position - touch1.position).magnitude;

                float zoomDelta = prevTouchDelta - touchDelta;

                if (zoomDelta > 0.01f || zoomDelta < -0.01f)
                {
                    FollowDistance += zoomDelta * 0.25f;
                    // Limit FollowDistance between min & max values.
                    FollowDistance = Mathf.Clamp(FollowDistance, MinFollowDistance, MaxFollowDistance);
                }
            }

            // Check MouseWheel to Zoom in-out
            if (mouseWheel < -0.01f || mouseWheel > 0.01f)
            {
                FollowDistance -= mouseWheel * 5.0f;
                // Limit FollowDistance between min & max values.
                FollowDistance = Mathf.Clamp(FollowDistance, MinFollowDistance, MaxFollowDistance);
            }
        }
    // Update is called once per frame
    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch      touch = Input.GetTouch(0);
            RaycastHit hit;
            Ray        ray = Camera.main.ScreenPointToRay(touch.position);
            if (Physics.Raycast(ray, out hit))
            {
                if (touch.phase == TouchPhase.Began)
                {
                    startPosition = touch.position;
                }

                if (touch.phase == TouchPhase.Moved)
                {
                    endPosition = touch.position;
                    if (endPosition != startPosition)
                    {
                        if (!doOnceSwipe)
                        {
                            differencePosition = startPosition - endPosition;
                            differencePosition.Normalize();

                            if (differencePosition.y > 0 && differencePosition.x > -0.5f && differencePosition.x < 0.5f)
                            {
                                IngredientProxy boxcast = hit.transform.GetComponent <IngredientProxy>();
                                if (boxcast != null)
                                {
                                    boxcast.OrbitAroundSideDown();
                                }
                                Debug.Log("Down swipe");
                            }

                            if (differencePosition.y < 0 && differencePosition.x > -0.5f && differencePosition.x < 0.5f)
                            {
                                IngredientProxy boxcast = hit.transform.GetComponent <IngredientProxy>();
                                if (boxcast != null)
                                {
                                    boxcast.OrbitAroundSideUp();
                                }
                                Debug.Log("Up swipe");
                            }

                            if (differencePosition.x < 0 && differencePosition.y > -0.5f && differencePosition.y < 0.5f)
                            {
                                IngredientProxy boxcast = hit.transform.GetComponent <IngredientProxy>();
                                if (boxcast != null)
                                {
                                    boxcast.OrbitAroundSideRight();
                                }
                                Debug.Log("Right swipe");
                            }

                            if (differencePosition.x > 0 && differencePosition.y > -0.5f && differencePosition.y < 0.5f)
                            {
                                IngredientProxy boxcast = hit.transform.GetComponent <IngredientProxy>();
                                if (boxcast != null)
                                {
                                    boxcast.OrbitAroundSideLeft();
                                }
                                Debug.Log("Left swipe");
                            }
                            doOnceSwipe = true;
                        }
                    }
                }

                if (touch.phase == TouchPhase.Ended)
                {
                    doOnceSwipe = false;
                }
            }
        }
    }
    void Update()
    {
        Touch[] touches = Input.touches;
        //This section for move the camera position only limited values .
        // You can Change the values for your requirements.
        //Here the camera will move with in your required portion on the screen.

        // This sets the bounderies.
        if (projectile.position.x > westBound)
        {
            projectile.position = new Vector3(westBound, projectile.position.y, projectile.position.z);
        }

        if (projectile.position.x < eastBound)
        {
            projectile.position = new Vector3(eastBound, projectile.position.y, projectile.position.z);
        }

        if (projectile.position.z < northBound)
        {
            projectile.position = new Vector3(projectile.position.x, projectile.position.y, northBound);
        }

        if (projectile.position.z > southBound)
        {
            projectile.position = new Vector3(projectile.position.x, projectile.position.y, southBound);
        }

        if (projectile.position.y < inZoomBound)
        {
            projectile.position = new Vector3(projectile.position.x, inZoomBound, projectile.position.z);
        }

        if (projectile.position.y > outZoomBound)
        {
            projectile.position = new Vector3(projectile.position.x, outZoomBound, projectile.position.z);
        }

        // camera movement with touch gestures. 3 fingers
        if (Input.touchCount == 3)
        {
            if (touches[0].phase == TouchPhase.Moved)
            {
                Vector2 delta = touches[0].deltaPosition;

                float position_x = delta.x * movesensitivityX * Time.deltaTime;
                float position_y = delta.y * movesensitivityY * Time.deltaTime;

                projectile.position = new Vector3(projectile.position.x + position_x, projectile.position.y, projectile.position.z + position_y);
            }
        }


        //This section for pinch Zooming on screen.
        if (Input.touchCount == 2)
        {
            Touch touch  = Input.GetTouch(0);
            Touch touch1 = Input.GetTouch(1);
            if (touch.phase == TouchPhase.Moved && touch1.phase == TouchPhase.Moved)
            {
                Vector2 curDist  = touch.position - touch1.position;
                Vector2 prevDist = (touch.position - touch.deltaPosition) - (touch1.position - touch1.deltaPosition);
                float   delta    = curDist.magnitude - prevDist.magnitude;
                Camera.main.transform.Translate(0, 0, delta * .5f);
            }
        }
    }
    /// <summary>
    /// Unity Update function.
    ///
    /// Mainly handle the touch event and place mark in place.
    /// </summary>
    public void Update()
    {
        if (m_saveThread != null && m_saveThread.ThreadState != ThreadState.Running)
        {
            // After saving an Area Description or mark data, we reload the scene to restart the game.
            _UpdateMarkersForLoopClosures();
            _SaveMarkerToDisk();
            #pragma warning disable 618
            Application.LoadLevel(Application.loadedLevel);
            #pragma warning restore 618
        }

        if (Input.GetKey(KeyCode.Escape))
        {
            #pragma warning disable 618
            Application.LoadLevel(Application.loadedLevel);
            #pragma warning restore 618
        }

        if (!m_initialized)
        {
            return;
        }

        if (EventSystem.current.IsPointerOverGameObject(0) || GUIUtility.hotControl != 0)
        {
            return;
        }

        if (Input.touchCount == 1)
        {
            Touch      t           = Input.GetTouch(0);
            Vector2    guiPosition = new Vector2(t.position.x, Screen.height - t.position.y);
            Camera     cam         = Camera.main;
            RaycastHit hitInfo;

            if (t.phase != TouchPhase.Began)
            {
                return;
            }

            if (m_selectedRect.Contains(guiPosition))
            {
                // do nothing, the button will handle it
            }
            else if (Physics.Raycast(cam.ScreenPointToRay(t.position), out hitInfo))
            {
                // Found a marker, select it (so long as it isn't disappearing)!
                GameObject tapped = hitInfo.collider.gameObject;
                if (!tapped.GetComponent <Animation>().isPlaying)
                {
                    m_selectedMarker = tapped.GetComponent <ARMarker>();
                }
            }
            else
            {
                // Place a new point at that location, clear selection
                m_selectedMarker = null;
                StartCoroutine(_WaitForDepthAndFindPlane(t.position));

                // Because we may wait a small amount of time, this is a good place to play a small
                // animation so the user knows that their input was received.
                RectTransform touchEffectRectTransform = Instantiate(m_prefabTouchEffect) as RectTransform;
                touchEffectRectTransform.transform.SetParent(m_canvas.transform, false);
                Vector2 normalizedPosition = t.position;
                normalizedPosition.x /= Screen.width;
                normalizedPosition.y /= Screen.height;
                touchEffectRectTransform.anchorMin = touchEffectRectTransform.anchorMax = normalizedPosition;
            }
        }
    }
Beispiel #42
0
    void Update()
    {
#if UNITY_ANDROID || UNITY_IPHONE
        if (Input.touchCount > 0)
        {
            Touch touch = Input.touches[0];

            switch (touch.phase)
            {
            case TouchPhase.Began:
                startPos = touch.position;
                CastRay(startPos);
                if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity, shootController.LogicPlaneStartSwipeMask))
                {
                    firstTouchPosition = hitInfo.point;
                    // Debug.Log(firstTouchPosition);
                    touchFirstLogicPlaneToStartSwipe = true;
                }
                break;

            case TouchPhase.Moved:
                float swipeDistHorizontal = (new Vector3(touch.position.x, 0, 0) - new Vector3(startPos.x, 0, 0)).magnitude;
                float swipeDistVertical   = (new Vector3(0, touch.position.y, 0) - new Vector3(0, startPos.y, 0)).magnitude;
                if (swipeDistVertical < minSpearSwipeDistVertical)
                {
                    canSwipeToAim = true;
                }
                //horizontal Swipe
                //Debug.Log("hor"+swipeDistHorizontal);
                // Debug.Log("ver"+swipeDistVertical);
                if (swipeDistHorizontal > minSwipeDistX && canSwipeToAim)
                {
                    float swipeValue = Mathf.Sign(touch.position.x - startPos.x);
                    if (swipeValue > 0 && !isTouch)    //to right swipe
                    {
                        Debug.Log("+");
                        isTouch = true;
                    }
                    else if (swipeValue < 0 && !isTouch && touchFirstLogicPlaneToStartSwipe)    //to left swipe
                    {
                        Debug.Log("-");
                        aimingAvaliable = true;
                        // Debug.Log(aimingAvaliable);
                        isTouch = true;
                    }
                }

                //add swipe to up
                if (swipeDistVertical > minSwipeDistY && swipeDistHorizontal < minSwipeDistX_Jump)
                {
                    float swipeValue = Mathf.Sign(touch.position.y - startPos.y);
                    if (swipeValue < 0 && !isTouch && !Grounded())
                    {
                        timeToNextJump = Time.time;
                        rb.velocity    = new Vector3(0, rb.velocity.y - jumpSpeed, 0);
                        isTouch        = true;
                    }
                    if (swipeValue > 0 && !isTouch && Grounded() && Time.time > timeToNextJump)
                    {
                        timeToNextJump      = Time.time + 1f;
                        enableJumpAnimation = true;
                        rb.velocity         = new Vector3(0, rb.velocity.y + jumpSpeed, 0);
                        isTouch             = true;
                    }
                }
                break;

            case TouchPhase.Ended:
                isTouch       = false;
                canSwipeToAim = false;
                touchFirstLogicPlaneToStartSwipe = false;
                break;
            }
        }
#endif
    }
Beispiel #43
0
    void Update()
    {
        //1 finger touch to rotate
        previousTouchPos = currentTouchPos;

        if (Input.touchCount == 1)
        {
            touch = Input.GetTouch(0);
            //Set a touchable area (does not allow user to touch on other UI part)
            if (touch.phase == TouchPhase.Moved && touch.position.x >= MIN_X && touch.position.x <= MAX_X && touch.position.y >= MIN_Y && touch.position.y <= MAX_Y)
            {
                currentTouchPos = Input.GetTouch(0).position.x;
                float distance = currentTouchPos - previousTouchPos;
                if (distance > 0)
                {
                    rotationY = Quaternion.Euler(
                        0f,
                        -Input.GetTouch(0).position.x *rotateSpeedModifier *Time.deltaTime,
                        0f);

                    transform.rotation = Quaternion.Lerp(transform.rotation, rotationY * transform.rotation, rotateSpeedModifier * Time.deltaTime);
                }
                else
                {
                    rotationY = Quaternion.Euler(
                        0f,
                        Input.GetTouch(0).position.x *rotateSpeedModifier *Time.deltaTime,
                        0f);

                    transform.rotation = Quaternion.Lerp(transform.rotation, rotationY * transform.rotation, rotateSpeedModifier * Time.deltaTime);
                }
            }
        }

        //2 finger pinch to scale
        if (Input.touchCount == 2)
        {
            var touchZero = Input.GetTouch(0);
            var touchOne  = Input.GetTouch(1);

            if (touchZero.phase == TouchPhase.Ended || touchZero.phase == TouchPhase.Canceled ||
                touchOne.phase == TouchPhase.Ended || touchOne.phase == TouchPhase.Canceled)
            {
                return;
            }

            if (touchZero.phase == TouchPhase.Began || touchOne.phase == TouchPhase.Began)
            {
                initialDistance = Vector2.Distance(touchZero.position, touchOne.position);
                initialScale    = transform.localScale;
            }
            else
            {
                var currentDistance = Vector2.Distance(touchZero.position, touchOne.position);
                if (Mathf.Approximately(initialDistance, 0))
                {
                    return;
                }
                var factor = currentDistance / initialDistance;

                transform.localScale = initialScale * factor;
            }
        }
    }
    private void TouchInput()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            if (m_iTouchID == -1)
            {
                m_iTouchID = touch.fingerId;
            }


            if (m_iTouchID != touch.fingerId)
            {
                return;
            }

            switch (touch.phase)
            {
            case TouchPhase.Began:
                m_vec3BeganPosi = touch.position;
                m_bPlayerReady  = true;
                EventManager.Instance.TriggerEvent <EventTouchActive>(new EventTouchActive(true, m_vec3BeganPosi));

                break;

            case TouchPhase.Moved:

                if (Vector3.Distance(m_vec3BeganPosi, touch.position) < 1)
                {
                    return;
                }

                Vector3 vec3Offset = (new Vector3(touch.deltaPosition.x, 0, 0));
                EventManager.Instance.TriggerEvent <EventTouchMove>(new EventTouchMove(true, vec3Offset));
                break;

            case TouchPhase.Stationary:
                EventManager.Instance.TriggerEvent <EventTouchMove>(new EventTouchMove(false, Vector3.zero));
                break;

            case TouchPhase.Ended:
                if (m_iTouchID != touch.fingerId)
                {
                    Debug.LogError("[TouchManager] Finger ID doesn't match");
                    return;
                }
                m_iTouchID = -1;

                if (m_bPlayerReady)
                {
                    //TODD: Stop any running process
                }
                m_bPlayerReady = false;

                EventManager.Instance.TriggerEvent <EventTouchMove>(new EventTouchMove(false, Vector3.zero));
                EventManager.Instance.TriggerEvent <EventTouchActive>(new EventTouchActive(false, Vector3.zero));
                //Debug.Log("[TouchInputManager] Touch phase: ENDED");
                break;

            case TouchPhase.Canceled:
                EventManager.Instance.TriggerEvent <EventTouchMove>(new EventTouchMove(false, Vector3.zero));
                EventManager.Instance.TriggerEvent <EventTouchActive>(new EventTouchActive(false, Vector3.zero));
                //Debug.Log("[TouchInputManager] Touch phase: CANCELLED");
                break;
            }
        }
        else
        {
            m_iTouchID = -1;
        }
    }
    void Update()
    {
        // If GUI Controls are disabled
        if (gwc.bStartGame &&
            touches.transform.localScale == Vector3.zero &&
            pause.transform.localScale == Vector3.zero)
        {
            // Swipe-Pan
            if (bReadyToPan &&
                (Input.touchCount == 1 &&
                 Input.GetTouch(0).phase == TouchPhase.Moved))
            {
                bReadyToPan = false;

                Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;

                // Convert touch panning to simple x & y input, i.e. GWCMove() in pMove
                if (Mathf.Abs(touchDeltaPosition.x) > Mathf.Abs(touchDeltaPosition.y))
                {
                    if (touchDeltaPosition.x > 0)
                    {
                        xInput = -1;
                    }
                    else if (touchDeltaPosition.x < 0)
                    {
                        xInput = 1;
                    }

                    playerMove.GWCMove(xInput, 0);
                }
                else if (Mathf.Abs(touchDeltaPosition.x) < Mathf.Abs(touchDeltaPosition.y))
                {
                    if (touchDeltaPosition.y > 0)
                    {
                        yInput = -1;
                    }
                    else if (touchDeltaPosition.y < 0)
                    {
                        yInput = 1;
                    }

                    playerMove.GWCMove(0, yInput);
                }
            }

            // Cycle Layers
            // If there is a double tap on the device... (and not on a character)
            // 05/15/2019 -- checking bReadyToPan means they're not panning atm
            if (Input.touchCount == 1 &&
                bReadyToPan)
            {
                Touch touch = Input.GetTouch(0);

                if (touch.phase == TouchPhase.Ended)
                {
                    tapCount += 1;
                }

                if (tapCount == 1)
                {
                    newTime = Time.time + maxDoubleTapTime;
                }
                else if (tapCount == 2 && Time.time <= newTime)
                {
                    for (int i = 0; i < gwc.charTiles.Length; i++)
                    {
                        gwc.charTiles[i].FlipLayer();
                    }

                    tapCount = 0;
                }
            }

            // 06/09/2019 -- Keep here to run after Cycle check (avoids cycling while panning quickly)
            if (Input.touchCount > 0 &&
                Input.GetTouch(0).phase == TouchPhase.Ended)
            {
                bReadyToPan = true;
            }

            // Reset double tap timer
            if (Time.time > newTime)
            {
                tapCount = 0;
            }

            // Pinch-Zoom
            // If there are two touches on the device...
            if (Input.touchCount == 2)
            {
                bPinchZooming = true;

                // Store both touches.
                Touch touchZero = Input.GetTouch(0);
                Touch touchOne  = Input.GetTouch(1);

                // Find the position in the previous frame of each touch.
                Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
                Vector2 touchOnePrevPos  = touchOne.position - touchOne.deltaPosition;

                // Find the magnitude of the vector (the distance) between the touches in each frame.
                float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
                float touchDeltaMag     = (touchZero.position - touchOne.position).magnitude;

                // Find the difference in the distances between each frame.
                float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;

                // If the camera is orthographic...
                if (mainCamera.orthographic)
                {
                    // ... change the orthographic size based on the change in distance between the touches.
                    mainCamera.orthographicSize += deltaMagnitudeDiff * orthoZoomSpeed;

                    // Make sure the orthographic size never drops below zero.
                    mainCamera.orthographicSize = Mathf.Clamp(mainCamera.orthographicSize, 0.875f, 5.642857f);
                }
                // DC 02/22/2019 -- This "should" never run
                else
                {
                    // Otherwise change the field of view based on the change in distance between the touches.
                    mainCamera.fieldOfView += deltaMagnitudeDiff * perspectiveZoomSpeed;

                    // Clamp the field of view to make sure it's between 0 and 180.
                    mainCamera.fieldOfView = Mathf.Clamp(mainCamera.fieldOfView, 0.1f, 179.9f);
                }

                // Adjust the scene transitioner
                sceneTransAnim.transform.localScale = new Vector2
                                                          (Mathf.Clamp((sceneTransAnim.transform.localScale.x + (deltaMagnitudeDiff * orthoZoomSpeed) * 1.5f), 1.5f, 9f),
                                                          Mathf.Clamp((sceneTransAnim.transform.localScale.y + (deltaMagnitudeDiff * orthoZoomSpeed) * 1.5f), 1.5f, 9f));
            }
            // Reset check to help avoid flipping tiles via MouseUp
            else if (Input.touchCount == 0 &&
                     bPinchZooming)
            {
                bPinchZooming = false;
            }
        }
    }
Beispiel #46
0
    public override void UpdateMe()
    {
        if (Input.touchCount == 0)
        {
            singleFingerActionsAllowed = true;
        }
        else if (Input.touchCount == 1)
        {
            Touch currTouch = Input.GetTouch(0);

            if (!singleFingerActionsAllowed)
            {
                return;
            }

            switch (currTouch.phase)
            {
            case TouchPhase.Began:
                manager.SetPossibleInteractingWithUI(true);
                hasDragged        = false;
                longPressHappened = false;
                dragStart         = currTouch.position;
                manager.SendCallbacks(callback => callback.OnPreparePrimaryDragVariables(dragStart));
                prevDragPosition   = dragStart;
                longPressActionUId = LeanTween.delayedCall(Controls.LongPressActionDelay, () => {
                    manager.SetPossibleInteractingWithUI(false);
                    manager.SendCallbacks(callback => callback.OnPrepareSecondaryDragVariables(dragStart));
                    manager.SendCallbacks(callback => callback.OnPickup(dragStart));
                    longPressHappened = true;
                }).uniqueId;
                break;

            case TouchPhase.Moved:
                hasDragged       = true;
                prevDragPosition = currTouch.position;
                LeanTween.cancel(longPressActionUId);
                if (longPressHappened)
                {
                    manager.SendCallbacks(callback => callback.OnItemDragAction(dragStart, currTouch.position));
                    manager.SendCallbacks(callback => callback.OnSecondaryDragAction(dragStart, currTouch.position));
                }
                else
                {
                    manager.SendCallbacks(callback => callback.OnPrimaryDragAction(dragStart, prevDragPosition));
                }
                break;

            case TouchPhase.Canceled:
            case TouchPhase.Ended:
                EndSingleTouch(currTouch);
                break;
            }
        }
        else if (Input.touchCount == 2)
        {
            Touch touchZero = Input.GetTouch(0);
            Touch touchOne  = Input.GetTouch(1);

            Vector3 touchZeroStart = Vector3.zero;

            switch (touchOne.phase)
            {
            case TouchPhase.Began:
                // When the other finger joins, cancel the contextual action along with other one-finger-only gestures.
                EndSingleTouch(touchZero);
                singleFingerActionsAllowed = false;
                break;

            case TouchPhase.Moved:
                Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
                Vector2 touchOnePrevPos  = touchOne.position - touchOne.deltaPosition;

                float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
                float touchDeltaMag     = (touchZero.position - touchOne.position).magnitude;

                float deltaMagnitudeDiff = (prevTouchDeltaMag - touchDeltaMag) * PerspectiveTouchZoomSpeed;
                manager.SendCallbacks(match => match.OnZoomChanged(deltaMagnitudeDiff));
                break;

            case TouchPhase.Canceled:
            case TouchPhase.Ended:
                break;
            }
        }
    }
Beispiel #47
0
 void Start()
 {
     animator = GetComponent <Animator>();
     touch    = touchArea.GetComponent <Touch>();
 }
Beispiel #48
0
    public void Swipe()
    {
        if (Input.touches.Length > 0)
        {
            Touch t = Input.GetTouch(0);
            if (t.phase == TouchPhase.Began)
            {
                //save began touch 2d point
                firstPressPos = new Vector2(t.position.x, t.position.y);
            }
            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)
                 * {
                 *  Debug.Log("up swipe");
                 * }*/
                //swipe down
                if (currentSwipe.y < -0.5f && notEnd)
                {
                    Debug.Log("down swipe");
                    notMenu = false;
                    dirY    = 1;
                    showSettMenu();
                }
                //swipe left
                else if (currentSwipe.x < -0.5f && notMenu && notEnd)
                {
                    Debug.Log("left swipe");
                    directionX = -1;
                    inkManager.ChooseLeft();
                }
                //swipe right
                else if (currentSwipe.x > 0.5f && notMenu && notEnd)
                {
                    Debug.Log("right swipe");
                    directionX = 1;
                    inkManager.ChooseRight();
                }
            }
        }

        if (Input.GetMouseButtonDown(0))
        {
            //save began touch 2d point
            firstPressPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        }
        if (Input.GetMouseButtonUp(1) && notMenu)
        {
            showMagazine();
        }
        if (Input.GetMouseButtonUp(0))
        {
            //save ended touch 2d point
            secondPressPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);

            //create vector from the two points
            currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);

            //normalize the 2d vector
            currentSwipe.Normalize();


            if (currentSwipe.y < -0.5f && notEnd)
            {
                Debug.Log("down swipe");
                notMenu = false;
                dirY    = 1;
                showSettMenu();
            }
            //swipe left
            else if (currentSwipe.x < -0.5f && notMenu && notEnd)
            {
                Debug.Log("left swipe");
                directionX = -1;
                inkManager.ChooseLeft();
            }
            //swipe right
            else if (currentSwipe.x > 0.5f && notMenu && notEnd)
            {
                Debug.Log("right swipe");
                directionX = 1;
                inkManager.ChooseRight();
            }
        }
    }
Beispiel #49
0
    /// <summary>
    /// Handles user input and functionality
    /// </summary>
    void Update()
    {
        // incriment seconds once every frame *** 1 second passed every 60 frames ***
        if (swinging)
        {
            sinceLastSwing += Time.deltaTime;
            // check to see if combo timer has run out
            if (sinceLastSwing >= comboTimer)
            {
                // reset our stats back to idle
                sinceLastSwing = 0;
                animTracker    = 0;
                anim.SetInteger("attack", animTracker);
                swinging     = false;
                comboEnabled = false;
                comboCount   = 0;
            }
        }
        // if the player has missed, add to the delay
        if (missed)
        {
            swingDelayTimer += Time.deltaTime;
            // if the timer has reached the delay, reset the stats
            if (swingDelayTimer >= swordDelay)
            {
                missed      = false;
                animTracker = 0;
                anim.SetInteger("attack", animTracker);
                swingDelayTimer = 0;
            }
        }
        // if the player is able to use input and not in the middle of recovering from a missed target
        else
        {
            // if the game is being played on a computer and not mobile
            if (gm.DESKTOPGAME == true)
            {
                // input for either of the player buttons to attack
                if (Input.GetKeyDown(KeyCode.Z) || Input.GetKeyDown(KeyCode.M))
                {
                    // input to see if player hit both keys at the same time
                    if (Input.GetKeyDown(KeyCode.Z) && Input.GetKeyDown(KeyCode.M))
                    {
                        DoubleInput();
                    }
                    // only one key was pressed, continue on from here
                    else
                    {
                        SingleInput();
                    }
                }
            }
            // if the game is being played on a mobile device and not a computer
            else if (gm.MOBILEGAME == true)
            {
                bool leftSideTouched  = false;
                bool rightSideTouched = false;
                // if there are any touches currently
                if (Input.touchCount > 0)
                {
                    // loop through all of the touches we have in the input manager right now
                    foreach (Touch touch in Input.touches)
                    {
                        // get the current touch we are checking
                        Touch currentTouch = touch;

                        // if it began this frame
                        if (currentTouch.phase == TouchPhase.Began)
                        {
                            // check to see if the left side of the screen has been touched
                            if (currentTouch.position.x < Screen.width / 2)
                            {
                                leftSideTouched = true;
                            }
                            // check to see if the right side of the screen has been touched
                            else if (currentTouch.position.x > Screen.width / 2)
                            {
                                rightSideTouched = true;
                            }
                        }
                    }
                    // loop ends and we see what our results are for either single touch or double touch
                    // if left side touched but right side was not touched
                    if (leftSideTouched == true && rightSideTouched == false)
                    {
                        SingleInput();
                    }
                    // if right side was touched but left side was not
                    else if (leftSideTouched == false && rightSideTouched == true)
                    {
                        SingleInput();
                    }
                    // both left and right side of the screen were touched
                    else if (leftSideTouched == true && rightSideTouched == true)
                    {
                        DoubleInput();
                    }
                }
            }
        }
        // some animation is being played that isn't idle
        if (animTracker > 0)
        {
            swipeRend.enabled = true;
        }
        // player isn't swinging at all
        else
        {
            swipeRend.enabled = false;
        }
    }
Beispiel #50
0
    /// <summary>
    /// Update touch-based events.
    /// </summary>

    public void ProcessTouches()
    {
        for (int i = 0; i < Input.touchCount; ++i)
        {
            Touch input = Input.GetTouch(i);

            currentTouchID = allowMultiTouch ? input.fingerId : 1;
            currentTouch   = GetTouch(currentTouchID);

            bool pressed   = (input.phase == TouchPhase.Began) || currentTouch.touchBegan;
            bool unpressed = (input.phase == TouchPhase.Canceled) || (input.phase == TouchPhase.Ended);
            currentTouch.touchBegan = false;

            if (pressed)
            {
                currentTouch.delta = Vector2.zero;
            }
            else
            {
                // Although input.deltaPosition can be used, calculating it manually is safer (just in case)
                currentTouch.delta = input.position - currentTouch.pos;
            }

            currentTouch.pos = input.position;
            if (!Raycast(currentTouch.pos, out lastHit))
            {
                hoveredObject = fallThrough;
            }
            if (hoveredObject == null)
            {
                hoveredObject = genericEventHandler;
            }
            currentTouch.current = hoveredObject;
            lastTouchPosition    = currentTouch.pos;

            // We don't want to update the last camera while there is a touch happening
            if (pressed)
            {
                currentTouch.pressedCam = currentCamera;
            }
            else if (currentTouch.pressed != null)
            {
                currentCamera = currentTouch.pressedCam;
            }

            // Double-tap support
            if (input.tapCount > 1)
            {
                currentTouch.clickTime = Time.realtimeSinceStartup;
            }

            // Process the events from this touch
            ProcessTouch(pressed, unpressed);

            // If the touch has ended, remove it from the list
            if (unpressed)
            {
                RemoveTouch(currentTouchID);
            }
            currentTouch = null;

            // Don't consider other touches
            if (!allowMultiTouch)
            {
                break;
            }
        }
    }
    void Update()
    {
        Touch touch;
        if (1 == Input.touchCount)
        {
            touch = Input.GetTouch(0);
            if (touch.phase == TouchPhase.Began)
            {
                RaycastHit hit;
                Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
                if (Physics.Raycast(ray, out hit))
                {
                    hit.transform.SendMessage("OnMouseDown");
                }
            }
            if (touch.phase == TouchPhase.Moved)
            {
                var tLimitXDeg = Mathf.Clamp(Input.touches[0].deltaPosition.x, -MaxXDegTouchVolecity, MaxXDegTouchVolecity);
                var tLimitYDeg = Mathf.Clamp(Input.touches[0].deltaPosition.y, -MaxYDegTouchVolecity, MaxYDegTouchVolecity);
                xDeg += tLimitXDeg * xSpeed * 0.02f;
                yDeg -= tLimitYDeg * ySpeed * 0.02f;
                yDeg = ClampAngle(yDeg, yMinLimit, yMaxLimit);
            }
            desiredRotation = Quaternion.Euler(yDeg, xDeg, 0);
            currentRotation = transform.rotation;
            rotation = Quaternion.Lerp(currentRotation, desiredRotation, 0.02f * zoomDampening);
            transform.rotation = rotation;
            idleSmooth = 0;
            idleTimer = 0;
        }
        else if (2 == Input.touchCount)
        {
            Touch newTouch1 = Input.GetTouch(0);
            Touch newTouch2 = Input.GetTouch(1);

            //第2点刚开始接触屏幕, 只记录,不做处理  
            if (newTouch2.phase == TouchPhase.Began)
            {
                oldTouch2 = newTouch2;
                oldTouch1 = newTouch1;
                return;
            }
            //计算老的两点距离和新的两点间距离,变大要放大模型,变小要缩放模型  
            float oldDistance = Vector2.Distance(oldTouch1.position, oldTouch2.position);
            float newDistance = Vector2.Distance(newTouch1.position, newTouch2.position);

            //两个距离之差,为正表示放大手势, 为负表示缩小手势  
            float offset = newDistance - oldDistance;
            desiredDistance -= offset * 0.001f * zoomSpeed * 0.125f * Mathf.Abs(desiredDistance);
            //记住最新的触摸点,下次使用  
            oldTouch1 = newTouch1;
            oldTouch2 = newTouch2;

        }
        else if (5 == Input.touchCount)
        {
            Screen.fullScreen = false;
        }
        else if (Input.GetAxis("Mouse ScrollWheel") != 0)
        {
            desiredDistance -= Input.GetAxis("Mouse ScrollWheel") * 0.5f * zoomSpeed * Mathf.Abs(desiredDistance);
        }
        //else if (Input.GetMouseButton(2) && Input.GetKey(KeyCode.LeftAlt) && Input.GetKey(KeyCode.LeftControl))
        //{
        //    desiredDistance -= Input.GetAxis("Mouse Y") * 0.02f * zoomSpeed * 0.125f * Mathf.Abs(desiredDistance);
        //}
        else if (Input.GetMouseButton(0))
        {
            var tLimitMouseXDeg = Mathf.Clamp(Input.GetAxis("Mouse X"), -MaxXDegMouseVolecity, MaxXDegMouseVolecity);
            xDeg += tLimitMouseXDeg * xSpeed * 0.1f;
            yDeg -= Input.GetAxis("Mouse Y") * ySpeed * 0.1f;
            yDeg = ClampAngle(yDeg, yMinLimit, yMaxLimit);

            desiredRotation = Quaternion.Euler(yDeg, xDeg, 0);
            currentRotation = transform.rotation;
            rotation = Quaternion.Lerp(currentRotation, desiredRotation, 0.02f * zoomDampening);
            transform.rotation = rotation;

            idleSmooth = 0;
            idleTimer = 0;

        }
        else
        {
            idleTimer += 0.02f;
            if (idleTimer > rotateOnOff && rotateOnOff > 0)
            {
                idleSmooth += (0.02f + idleSmooth) * 0.005f;
                idleSmooth = Mathf.Clamp(idleSmooth, 0, 1);
                xDeg += xSpeed * 0.001f * idleSmooth;
            }
            yDeg = ClampAngle(yDeg, yMinLimit, yMaxLimit);
            desiredRotation = Quaternion.Euler(yDeg, xDeg, 0);
            currentRotation = transform.rotation;
            rotation = Quaternion.Lerp(currentRotation, desiredRotation, 0.02f * zoomDampening * 2);
            transform.rotation = rotation;
        }

        desiredDistance = Mathf.Clamp(desiredDistance, minDistance, maxDistance);
        currentDistance = Mathf.Lerp(currentDistance, desiredDistance, 0.02f  * zoomDampening);
		position = targetObject.position - (rotation * Vector3.forward * currentDistance + targetOffset);
        transform.position = position;
    }
Beispiel #52
0
    private void Update()
    {
        if (startGame)
        {
            if (isActive)
            {
                StartCoroutine(FruitInstance());
            }


            if (Input.touchCount > 0)
            {
                Touch   touch         = Input.GetTouch(0);
                Vector2 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);

                if (touch.phase == TouchPhase.Began)
                {
                    Collider2D touchedCollider = Physics2D.OverlapPoint(touchPosition);
                    for (int i = 0; i < listCol.Count; i++)
                    {
                        if (listCol[i] == touchedCollider)
                        {
                            if (listCol[i].tag == "CitronVert")
                            {
                                FindObjectOfType <AudioManager>().Play("BonFruit");
                                if (countWin >= 5)
                                {
                                    WinStrick();
                                    panelWinStrick.SetActive(true);
                                }

                                else
                                {
                                    GameManager.instance.UpdateScore(1);
                                }
                                countWin += 1;
                                countLose = 0;
                                panelLoseStrick.SetActive(false);
                            }
                            else if (listCol[i].tag == "RainbowCitron")
                            {
                                FindObjectOfType <AudioManager>().Play("BonFruit");
                                if (countWin >= 5)
                                {
                                    GameManager.instance.UpdateScore(8);
                                    panelWinStrick.SetActive(true);
                                }

                                else
                                {
                                    GameManager.instance.UpdateScore(4);
                                }
                                countWin += 1;
                                countLose = 0;
                                panelLoseStrick.SetActive(false);
                            }
                            else
                            {
                                FindObjectOfType <AudioManager>().Play("MauvaisFruit");
                                if (countLose >= 5)
                                {
                                    LoseStrick();
                                    panelLoseStrick.SetActive(true);
                                }

                                else
                                {
                                    GameManager.instance.UpdateScore(-1);
                                }
                                countLose += 1;
                                countWin   = 0;
                                panelWinStrick.SetActive(false);
                            }

                            Destroy(listCol[i].gameObject);
                            listCol.RemoveAt(i);
                            //listPos.RemoveAt(i);
                        }
                    }
                }
            }
        }
    }
Beispiel #53
0
	void Update ()
	{	//int x = 1;
		for (int i = 0; i < Input.touchCount; i++) {
			Touch touch = Input.GetTouch (i);
			if (touch.phase == TouchPhase.Ended) {
				Ray ray = Camera.main.ScreenPointToRay (touch.position);
				RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction);
				if (hit.collider != null) {
					//	D		
					if (hit.collider.tag == "Player") {   
						#region Hit Player
						
						//	Destroy (GameObject.Find ("FadePlayer" + x.ToString ()));
						WallScript wallsc = hit.transform.GetComponent<WallScript> ();
						if (wallsc) { 
							selectedwall = hit.transform.gameObject;
							selected=wallsc.id;
							fadeeverything ();
							m1 = wallsc.PossibleLeftMove ();
							m2 = wallsc.PossibleRightMove ();
							
							fadeit = GameObject.Find ("FadePlayer" + m1.ToString ());
							FaderScript fadescript = fadeit.GetComponent<FaderScript> ();
							WallScript tofade = fadeit.GetComponent<WallScript> ();
							if(wallsc.owner==0)
							{
								if (tofade.owner == wallsc.id || tofade.owner == 0)
									fadescript.fading = true;
								fadeit = GameObject.Find ("FadePlayer" + m2.ToString ());
								tofade = fadeit.GetComponent<WallScript> ();
								fadescript = fadeit.GetComponent<FaderScript> ();
								if (tofade.owner == wallsc.id || tofade.owner == 0)
									fadescript.fading = true;
							}
							else
							{
								if (tofade.owner == wallsc.id)
									fadescript.fading = true;
								fadeit = GameObject.Find ("FadePlayer" + m2.ToString ());
								tofade = fadeit.GetComponent<WallScript> ();
								fadescript = fadeit.GetComponent<FaderScript> ();
								if (tofade.owner == wallsc.id)
									fadescript.fading = true;
								
							}
							
						}
					}
					#endregion
					#region Hit RedWall
					else if (hit.collider.tag == "Redwall"&&selectedwall!=null) {
						WallScript ownerid = selectedwall.GetComponent<WallScript> ();
						WallScript getid = hit.collider.gameObject.GetComponent<WallScript> ();
						if (ownerid.owner == 0) {
							
							if (getid.owner == 0) {
								

								if (getid.id == m1 || getid.id == m2) {
									getid.owner = selected;
									ownerid.owner = 1;
									Vector3 savepos = selectedwall.transform.position;
									selectedwall.transform.position = hit.collider.transform.position;
									hit.collider.transform.position = savepos;
								} else {
									selected = 0;
									//		m1 = 0;
									//		m2 = 0;
									fadeeverything ();
								}
							} else if (getid.owner == selected) {   
								
								getid.owner = 0;
								if (getid.id == m1 || getid.id == m2) {
									ownerid.owner = 1;
									Vector3 savepos = selectedwall.transform.position;
									selectedwall.transform.position = hit.collider.transform.position;
									hit.collider.transform.position = savepos;
								} else {
									//selected = 0;
									//	m1 = 0;
									//	m2 = 0;
									fadeeverything ();
								}
								
							}
						} else {
							if (getid.owner == selected) {   
								
								getid.owner = 0;
								if (getid.id == m1 || getid.id == m2) {
									ownerid.owner = 0;
									Vector3 savepos = selectedwall.transform.position;
									selectedwall.transform.position = hit.collider.transform.position;
									hit.collider.transform.position = savepos;
									
								}	
							}
							
						}
						
					}
					#endregion
				}
				else  {
					//	selectedwall=null;
					fadeeverything();
				}
			}
			else { 
				if (touch.phase == TouchPhase.Began)
				{
					Debug.Log("I'm Here");
					Ray ray = Camera.main.ScreenPointToRay (touch.position);
					RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction);
					if (hit.collider != null) {
						//	D		
						if (hit.collider.tag == "Player") {   						
							//	Destroy (GameObject.Find ("FadePlayer" + x.ToString ()));
							WallScript wallsc = hit.transform.GetComponent<WallScript> ();
							if (wallsc) { 
								selectedwall = hit.transform.gameObject;
								selected=wallsc.id;
								fadeeverything ();
								m1 = wallsc.PossibleLeftMove ();
								m2 = wallsc.PossibleRightMove ();
								
								fadeit = GameObject.Find ("FadePlayer" + m1.ToString ());
								FaderScript fadescript = fadeit.GetComponent<FaderScript> ();
								WallScript tofade = fadeit.GetComponent<WallScript> ();
								if(wallsc.owner==0)
								{
									if (tofade.owner == wallsc.id || tofade.owner == 0)
										fadescript.fading = true;
									fadeit = GameObject.Find ("FadePlayer" + m2.ToString ());
									tofade = fadeit.GetComponent<WallScript> ();
									fadescript = fadeit.GetComponent<FaderScript> ();
									if (tofade.owner == wallsc.id || tofade.owner == 0)
										fadescript.fading = true;
								}
								else
								{
									if (tofade.owner == wallsc.id)
										fadescript.fading = true;
									fadeit = GameObject.Find ("FadePlayer" + m2.ToString ());
									tofade = fadeit.GetComponent<WallScript> ();
									fadescript = fadeit.GetComponent<FaderScript> ();
									if (tofade.owner == wallsc.id)
										fadescript.fading = true;
									
								}
								
							}
						}	
					}
				}
				else if (touch.phase == TouchPhase.Moved)
				{
					// Move the trail
					Ray ray = Camera.main.ScreenPointToRay (touch.position);
					RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction);
					if (hit.collider != null) {
						//	D		
						if (hit.collider.tag == "Redwall"&&selectedwall!=null) {
							WallScript ownerid = selectedwall.GetComponent<WallScript> ();
							WallScript getid = hit.collider.gameObject.GetComponent<WallScript> ();
							if (ownerid.owner == 0) {
								
								if (getid.owner == 0) {
									

									if (getid.id == m1 || getid.id == m2) {
										getid.owner = selected;
										ownerid.owner = 1;
										Vector3 savepos = selectedwall.transform.position;
										selectedwall.transform.position = hit.collider.transform.position;
										hit.collider.transform.position = savepos;
									} else {
										selected = 0;
										//m1 = 0;
										//m2 = 0;
										fadeeverything ();
									}
								} else if (getid.owner == selected) {   
									
									getid.owner = 0;
									if (getid.id == m1 || getid.id == m2) {
										ownerid.owner = 1;
										Vector3 savepos = selectedwall.transform.position;
										selectedwall.transform.position = hit.collider.transform.position;
										hit.collider.transform.position = savepos;
									} else {
										//selected = 0;
										//	m1 = 0;
										//	m2 = 0;
										fadeeverything ();
									}
									
								}
							} else {
								if (getid.owner == selected) {   
									
									getid.owner = 0;
									if (getid.id == m1 || getid.id == m2) {
										ownerid.owner = 0;
										Vector3 savepos = selectedwall.transform.position;
										selectedwall.transform.position = hit.collider.transform.position;
										hit.collider.transform.position = savepos;
										
									}
									
									
									
								}
								
							}
							
						}
						
					}
				}
				else if (touch.phase == TouchPhase.Ended)
				{
					// Clear known trails
					
					
				}
				
				
				
			}	
		}
		
	}
        /// The Unity Update method.
        /// </summary>
        public void Update()
        {
            print("Print Start");
            Debug.Log("log Start");
            // Exit the app when the 'back' button is pressed.
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }

            // Check that motion tracking is tracking.
            if (Session.Status != SessionStatus.Tracking)
            {
                return;
            }

            // Get updated augmented images for this frame.
            Session.GetTrackables <AugmentedImage>(m_TempAugmentedImages, TrackableQueryFilter.Updated);

            // Create visualizers and anchors for updated augmented images that are tracking and do not previously
            // have a visualizer. Remove visualizers for stopped images.

            foreach (Touch touch in Input.touches)
            {
                Input.GetTouch(0);
                print(touch.tapCount);
                print("Hello");
                Debug.Log("Touching");
            }
            foreach (var image in m_TempAugmentedImages)
            {
                AugmentedImageVisualizer visualizer = null;
                m_Visualizers.TryGetValue(image.DatabaseIndex, out visualizer);
                if (image.TrackingState == TrackingState.Tracking && visualizer == null)
                {
                    AugmentedImageVisualizerPrefab.gameObject.SetActive(true);
                    // Create an anchor to ensure that ARCore keeps tracking this augmented image.
                    Anchor anchor = image.CreateAnchor(image.CenterPose);
                    //visualizer = (AugmentedImageVisualizer)Instantiate(AugmentedImageVisualizerPrefab, anchor.transform);

                    visualizer = (AugmentedImageVisualizer)Instantiate(prefabs[image.DatabaseIndex], anchor.transform);


                    visualizer.Image = image;
                    m_Visualizers.Add(image.DatabaseIndex, visualizer);
                }
                if (Input.touchCount > 0)
                {
                    Touch touch = Input.GetTouch(0);
                    m_Visualizers.Remove(image.DatabaseIndex);
                    GameObject.Destroy(visualizer.gameObject);
                }
                else if ((image.TrackingState == TrackingState.Stopped || image.TrackingState == TrackingState.Paused) && visualizer != null)
                {
                    m_Visualizers.Remove(image.DatabaseIndex);
                    GameObject.Destroy(visualizer.gameObject);
                }
            }

            // Show the fit-to-scan overlay if there are no images that are Tracking.
            foreach (var visualizer in m_Visualizers.Values)
            {
                if (visualizer.Image.TrackingState == TrackingState.Tracking)
                {
                    FitToScanOverlay.SetActive(false);
                    return;
                }
            }

            FitToScanOverlay.SetActive(true);
        }
Beispiel #55
0
    // Update is called once per frame
    void Update()
    {
        GameObject body = GameObject.Find("body");

        Touch[] myTouchesAux = Input.touches;
        Touch[] myTouches    = new Touch[members.Length];

        for (int i = 0; i < myTouchesAux.Length; i++)
        {
            float[] distancias = new float[anchors.Length];
            for (int j = 0; j < anchors.Length; j++)
            {
                distancias[j] = Mathf.Abs(Distance2Points(new Vector2(ConversionX(myTouchesAux[i].position.x), ConversionY(myTouchesAux[i].position.y)), anchorsDefaultPosition[j]));
            }
            for (int j = 0; j < anchors.Length; j++)
            {
                if (Mathf.Min(distancias) == distancias[j])
                {
                    myTouches[j] = myTouchesAux[i];
                }
            }
        }


        var mousePosition = Input.mousePosition;

        //Debug.Log(mousePosition);

        Vector3[]    newPositions            = new Vector3[4];
        Vector3[]    newScales               = new Vector3[4];
        Quaternion[] newRotations            = new Quaternion[4];
        Vector3[]    touchPositionsConverted = new Vector3[4];
        Vector3[]    membersStart            = new Vector3[4];

        membersStart[0] = new Vector3(body.transform.position.x + 0.6f, body.transform.position.y + 0.45f, 0);
        membersStart[1] = new Vector3(body.transform.position.x - 0.6f, body.transform.position.y + 0.45f, 0);
        membersStart[2] = new Vector3(body.transform.position.x + 0.6f, body.transform.position.y - 0.45f, 0);
        membersStart[3] = new Vector3(body.transform.position.x - 0.6f, body.transform.position.y - 0.45f, 0);

        for (int i = 0; i < membersStart.Length; i++)
        {
            Debug.DrawLine(membersStart[i], new Vector3(ConversionX(mousePosition.x), ConversionY(mousePosition.y), 0), Color.black);
        }


        for (int i = 0; i < myTouches.Length; i++)
        {
            if (myTouches[i].position == new Vector2(0, 0))
            {
                members[i].transform.position   = membersDefaultPosition[i];
                members[i].transform.rotation   = membersDefaultRotation[i];
                members[i].transform.localScale = membersDefaultScale[i];

                anchors[i].transform.position   = anchorsDefaultPosition[i];
                anchors[i].transform.rotation   = anchorsDefaultRotation[i];
                anchors[i].transform.localScale = anchorsDefaultScale[i];
            }
            else
            {
                touchPositionsConverted[i] = new Vector3(ConversionX(myTouches[i].position.x), ConversionY(myTouches[i].position.y), 0);
                Vector3 middlePoint = new Vector3((touchPositionsConverted[i].x - membersStart[i].x) / 2, (touchPositionsConverted[i].y - membersStart[i].y) / 2, 0);
                newScales[i]    = new Vector3(0.2f, (1f * (Distance2Points(membersStart[i].x, touchPositionsConverted[i].x, membersStart[i].y, touchPositionsConverted[i].y)) / 1.5f), 1);
                newPositions[i] = new Vector3(membersStart[i].x + middlePoint.x, membersStart[i].y + middlePoint.y, 0);
                float angleRads    = Mathf.Atan2((touchPositionsConverted[i].y - membersStart[i].y), (touchPositionsConverted[i].x - membersStart[i].x));
                float angleDegrees = 90 - (180f * angleRads) / Mathf.PI;
                newRotations[i] = Quaternion.AngleAxis(-angleDegrees, new Vector3(0, 0, 1));

                members[i].transform.position   = newPositions[i];
                members[i].transform.localScale = newScales[i];
                members[i].transform.rotation   = newRotations[i];
                anchors[i].transform.position   = new Vector3(touchPositionsConverted[i].x, touchPositionsConverted[i].y, 0);
                anchors[i].transform.localScale = new Vector3(0.2f, 1, 1);
                anchors[i].transform.rotation   = newRotations[i];
            }
        }

        /*
         * for (int i = 0; i < myTouches.Length; i++)
         * {
         *  touchPositionsConverted[i] = new Vector3(ConversionX(myTouches[i].position.x), ConversionY(myTouches[i].position.y), 0);
         *  Vector3 middlePoint = new Vector3((touchPositionsConverted[i].x - membersStart[i].x) / 2, (touchPositionsConverted[i].y - membersStart[i].y) / 2, 0);
         *  newScales[i] = new Vector3(0.2f, (1f * (Distance2Points(membersStart[i].x, touchPositionsConverted[i].x, membersStart[i].y, touchPositionsConverted[i].y)) / 1.5f), 1);
         *  newPositions[i] = new Vector3(membersStart[i].x + middlePoint.x, membersStart[i].y + middlePoint.y, 0);
         *  float angleRads = Mathf.Atan2((touchPositionsConverted[i].y - membersStart[i].y), (touchPositionsConverted[i].x - membersStart[i].x));
         *  float angleDegrees = 90 - (180f * angleRads) / Mathf.PI;
         *  newRotations[i] = Quaternion.AngleAxis(-angleDegrees, new Vector3(0, 0, 1));
         * }
         *
         * for(int i = 0; i < myTouches.Length; i++)
         * {
         *  members[i].transform.position = newPositions[i];
         *  members[i].transform.localScale = newScales[i];
         *  members[i].transform.rotation = newRotations[i];
         *  anchors[i].transform.position = new Vector3(touchPositionsConverted[i].x, touchPositionsConverted[i].y, 0);
         *  anchors[i].transform.localScale = new Vector3(0.2f, 1, 1);
         *  anchors[i].transform.rotation = newRotations[i];
         * }
         */

        //Para fazer Debug, controlar braço direito com mouse

        /*
         * float[] distancias = new float[anchors.Length];
         * Debug.Log(new Vector2(ConversionX(mousePosition.x), ConversionY(mousePosition.y)));
         * for(int i = 0; i < anchors.Length; i++)
         * {
         *  distancias[i] = Distance2Points(anchors[i].transform.position, new Vector2(ConversionX(mousePosition.x), ConversionY(mousePosition.y)));
         *  Debug.Log("distancia " + i + " = " + distancias[i]);
         * }
         * int myThing = 0;
         * for (int i = 0; i < distancias.Length; i++)
         * {
         *  if(Mathf.Min(distancias) == distancias[i])
         *  {
         *      myThing = i;
         *      Debug.Log("ancora a fazer snap = " + myThing);
         *  }
         * }
         * Vector3 meioPonto = new Vector3((ConversionX(mousePosition.x) - membersStart[myThing].x) / 2, (ConversionY(mousePosition.y) - membersStart[myThing].y) / 2, 0);
         * Vector3 novaPosicao = new Vector3(membersStart[myThing].x + meioPonto.x, membersStart[myThing].y + meioPonto.y);
         * Vector3 novaEscala = new Vector3(0.2f, (1f * (Distance2Points(membersStart[myThing].x, ConversionX(mousePosition.x), membersStart[myThing].y, ConversionY(mousePosition.y))) / 1.5f), 1);
         * float anguloRads = Mathf.Atan2((ConversionY(mousePosition.y) - membersStart[myThing].y), (ConversionX(mousePosition.x) - membersStart[myThing].x));
         * float anguloGraus = 90 - (180f * anguloRads) / Mathf.PI;
         * Quaternion novaRotacao = Quaternion.AngleAxis(-anguloGraus, new Vector3(0, 0, 1));
         *
         * members[myThing].transform.position = novaPosicao;
         * members[myThing].transform.localScale = novaEscala;
         * members[myThing].transform.rotation = novaRotacao;
         * anchors[myThing].transform.rotation = novaRotacao;
         * anchors[myThing].transform.position = new Vector3(ConversionX(mousePosition.x), ConversionY(mousePosition.y));
         * anchors[myThing].transform.localScale = new Vector3(0.2f, 1, 1);
         */
    }
    /// <summary>
    /// Update location marker state.
    /// </summary>
    private void _UpdateLocationMarker()
    {
        if (Input.touchCount == 2)
        {
            return;
        }

        if (Input.touchCount == 1 || Input.GetMouseButtonDown(1))
        {
            // Single tap -- place new location or select existing location.

            Vector2 pos = new Vector2();
            if (Input.touchCount == 1)
            {
                Touch t = Input.GetTouch(0);
                pos = t.position;
                if (t.phase != TouchPhase.Began ||
                    UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(t.fingerId))
                {
                    return;
                }
            }
            else
            {
                if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
                {
                    return;
                }
                pos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
            }

            if (GameGlobals.PropertiesPanelOpen)
            {
                GameGlobals.SetPropertiesOpen(false);
                return;
            }

            Vector2    guiPosition = new Vector2(pos.x, Screen.height - pos.y);
            Camera     cam         = Camera.main;
            RaycastHit hitInfo;

            if (m_selectedRect.Contains(guiPosition) || m_hideAllRect.Contains(guiPosition))
            {
                // do nothing, the button will handle it
            }
            else if (Physics.Raycast(cam.ScreenPointToRay(pos), out hitInfo, 10, 1 << _PrefabObjLayer))
            {
                // Found a prefab, select it (so long as it isn't disappearing)!
                GameObject tapped = hitInfo.collider.transform.root.gameObject;
                //Debug.Log(tapped.name + " tapped!");
                m_selectedPrefab = tapped.GetComponent <ARSelectable>();
                m_selectedPrefab.MakeSelected();

                //if (!tapped.GetComponent<Animation>().isPlaying)
                //{
                //    m_selectedPrefab = tapped.GetComponent<PrefabObject>();
                //}
            }
            else
            {
                // Place a new point at that location, clear selection
                m_selectedPrefab = null;
                GameGlobals.ChangeSelected(Enums.SelectionType.NONE);

                StartCoroutine(_WaitForDepthAndFindPlane(pos));

                // Because we may wait a small amount of time, this is a good place to play a small
                // animation so the user knows that their input was received.
                RectTransform touchEffectRectTransform = (RectTransform)Instantiate(m_prefabTouchEffect);
                touchEffectRectTransform.transform.SetParent(m_canvas.transform, false);
                Vector2 normalizedPosition = pos;
                normalizedPosition.x /= Screen.width;
                normalizedPosition.y /= Screen.height;
                touchEffectRectTransform.anchorMin = touchEffectRectTransform.anchorMax = normalizedPosition;
            }
        }
    }
Beispiel #57
0
    void Update()
    {
//		if(PlayerPrefs.GetInt("stopButton") == 1){
//			isDisableBt = false;
//		}
//
//		if(PlayerPrefs.GetInt("stopButton") == 0){
//			isDisableBt = true;
//		}


        //r shortcut quests in bool

//		buttonsA.pixelInset = new Rect (Screen.width*0.85f, Screen.height*0.1f, (Screen.width)*0.1f, (Screen.height)*0.18f);
//		Acts.pixelInset = new Rect (Screen.width*0.51f, Screen.height*1.3f, (Screen.width)*-0.81f, (Screen.height)*-0.82f);//0.71
        Objectivez.pixelInset = new Rect(Screen.width * 0.78f, Screen.height * 0.81f, (Screen.width) * 0.2f, (Screen.height) * 0.17f);  //GUI OBJECTIVES
//		textWindowz.pixelInset = new Rect (Screen.width*0f, Screen.height*0f, (Screen.width)*0.7f, (Screen.height)*0.37f);
//		objectivesz.pixelInset = new Rect(Screen.width*0.75f,Screen.height*0.75f,(Screen.width)*-0.5f,(Screen.height)*-0.5f);//BACKGROUND OBJECTIVES
//		itemHolderz.pixelInset = new Rect(Screen.width*0.0f, Screen.height*0.35f, (Screen.width)*0.2f, (Screen.height)*0.45f);
//
//		displayTickerz.pixelOffset= new Vector2(Screen.width*0.27f,Screen.height*0.7f);
//
//


        if (onQuest1)
        {
            showTicker("Go to UNIVERSITY OF\nMADRID and talk to\nthe RECEPTIONIST");
        }
        if (onQuestFinish)
        {
            newQuest.displayEnd("Quest Finished!");
            showTicker("");
        }


        if (isDisableBt == true)
        {
            if (Input.touchCount > 0)
            {
                Touch t = Input.GetTouch(0);

                if (t.phase == TouchPhase.Began)
                {
                    if (bt.HitTest(t.position, Camera.main))
                    {
                        touch.stopMovements();
                        if (NPC1)
                        {
                            isButtonPressedNPC = true;
                            isTextWindow       = true;
                            if (onQuest1 == true)
                            {
                                currentLine1++;
                            }
                            else if (onQuest6 == true)
                            {
                                currentLine6++;
                            }
                            else
                            {
                                otherLine1++;
                            }
                        }

                        if (NPC2)
                        {
                            isButtonPressedNPC = true;
                            isTextWindow       = true;
                            if (onQuest2 == true)
                            {
                                currentLine2++;
                            }
                            else
                            {
                                otherLine1++;
                            }
                        }

                        if (NPC3)
                        {
                            isButtonPressedNPC = true;
                            isTextWindow       = true;
                            if (onQuest3 == true)
                            {
                                currentLine3++;
                            }
                            else
                            {
                                otherLine1++;
                            }
                        }

                        if (NPC4)
                        {
                            isButtonPressedNPC = true;
                            isTextWindow       = true;
                            if (onQuest4 == true)
                            {
                                currentLine4++;
                            }
                            else
                            {
                                otherLine1++;
                            }
                        }

                        if (NPC5)
                        {
                            isButtonPressedNPC = true;
                            isTextWindow       = true;
                            if (onQuest5 == true)
                            {
                                currentLine5++;
                            }
                            else
                            {
                                otherLine1++;
                            }
                        }

                        if (NPC6)
                        {
                            isButtonPressedNPC = true;
                            isTextWindow       = true;
                            if (onQuest7 == true)
                            {
                                currentLine7++;
                            }
                            else
                            {
                                otherLine1++;
                            }
                        }
                        isHide = true;
                    }
                }
            }
        }

        /*
         * if (Input.GetMouseButtonDown (0)) {
         *
         *      if (bt.HitTest (Input.mousePosition, Camera.main)) {
         *              if(NPC1){
         *                      isButtonPressedNPC = true;
         *                      if(onQuest1 == true){
         *                              currentLine1++;
         *                      }else if(onQuest6 == true){
         *                              currentLine6++;
         *                      }else{
         *                              otherLine1++;
         *                      }
         *              }
         *
         *              if(NPC2){
         *                      isButtonPressedNPC = true;
         *                      if(onQuest2 == true){
         *                              currentLine2++;
         *                      }else{
         *                              otherLine1++;
         *                      }
         *              }
         *
         *              if(NPC3){
         *                      isButtonPressedNPC = true;
         *                      if(onQuest3 == true){
         *                              currentLine3++;
         *                      }else{
         *                              otherLine1++;
         *                      }
         *              }
         *
         *              if(NPC4){
         *                      isButtonPressedNPC = true;
         *                      if(onQuest4 == true){
         *                              currentLine4++;
         *                      }else{
         *                              otherLine1++;
         *                      }
         *              }
         *
         *              if(NPC5){
         *                      isButtonPressedNPC = true;
         *                      if(onQuest5 == true){
         *                              currentLine5++;
         *                      }else{
         *                              otherLine1++;
         *                      }
         *              }
         *
         *              if(NPC6){
         *                      isButtonPressedNPC = true;
         *                      if(onQuest7 == true){
         *                              currentLine7++;
         *                      }else{
         *                              otherLine1++;
         *                      }
         *              }
         *
         *              isHide = true;
         *      }
         * }
         */

        Transition();
        HideTextures();
        HideBt();
        HideTextWindow();
    }
Beispiel #58
0
    void HandleTouchMoved(Touch touch)
    {
        if (m_activeDragObject != null)
        {
            //Get current cell finger is on
            GridCell cell = GetCellFromRay(touch, m_cellLayer);

            //Store the last position
            Vector3 lastPos;

            //If this is a valid cell
            if (cell != null)
            {
                //Store last position
                lastPos = m_activeDragObject.transform.position;

                //Move boat to new position
                m_activeDragObject.transform.position = cell.transform.position;

                BoatComponent[] boats = m_activeDragObject.GetComponentsInChildren <BoatComponent>();

                bool allCellsFree = CheckIfFree(boats);

                //If all the cells are free
                if (allCellsFree)
                {
                    //Set the new position of the object
                    m_activeDragObject.transform.position = cell.transform.position;

                    //Make sure they're set as now on the grid
                    foreach (BoatComponent b in boats)
                    {
                        b.m_bOnGrid = true;
                    }

                    if (m_lastActiveCells.Count > 0)
                    {
                        if (m_lastActiveCells[0] != null)
                        {
                            //If we have moved onto a new grid cell
                            if (cell.gameObject != m_lastActiveCells[0].gameObject)
                            {
                                //Set the old cells to be free
                                foreach (GridCell c in m_lastActiveCells)
                                {
                                    c.m_bIsFree     = true;
                                    c.m_blockingObj = null;
                                }
                            }
                        }
                    }

                    //Clear the last active cells list
                    m_lastActiveCells.Clear();
                    m_lastActiveCells.Capacity = 0;

                    //Loop through the boats
                    foreach (BoatComponent b in boats)
                    {
                        //Get every cell the boat is touching
                        GridCell bCell = GridCellManager.instance.GetGridCellByPosition(b.transform.position);
                        //Add it to the last active cell list
                        m_lastActiveCells.Add(bCell);
                        bCell.m_bIsFree     = false;
                        bCell.m_blockingObj = b.transform.parent.gameObject;
                    }
                }
                //If the cells aren't free then move back to original position
                else
                {
                    m_activeDragObject.transform.position = lastPos;
                }
            }

            //Move boat object when not attached to the grid
            else
            {
                foreach (GridCell lastCell in m_lastActiveCells)
                {
                    lastCell.m_bIsFree     = true;
                    lastCell.m_blockingObj = null;
                }

                //GridCellManager.instance.SetGridCell(m_lastActiveCell);

                Ray        ray = Camera.main.ScreenPointToRay(touch.position);
                RaycastHit hit;

                if (Physics.Raycast(ray, out hit, Mathf.Infinity))
                {
                    if (hit.transform.tag == "GroundingPlane")
                    {
                        BoatComponent[] boats = m_activeDragObject.GetComponentsInChildren <BoatComponent>();
                        foreach (BoatComponent b in boats)
                        {
                            b.m_bOnGrid = false;
                        }
                        m_activeDragObject.transform.position = hit.point;
                    }
                }
            }
        }
    }
Beispiel #59
0
    private void Update()
    {
        int count = Input.touchCount;

        /* Adjust the tap time window while it still available */
        if (tapTimeWindow > 0)
        {
            tapTimeWindow -= Time.deltaTime;
        }
        else
        {
            tapCount = 0;
        }

        if (count == 0)
        {
            Restart();
        }
        else
        {
            for (int i = 0; i < count; i++)
            {
                Touch   touch       = Input.GetTouch(i);
                Vector2 guiTouchPos = touch.position - guiTouchOffset;

                bool shouldLatchFinger = false;
                if (touchPad && touchZone.Contains(touch.position))
                {
                    shouldLatchFinger = true;
                }
                else if (gui.HitTest(touch.position))
                {
                    shouldLatchFinger = true;
                }

                /* Latch the finger if this is a new touch */
                if (shouldLatchFinger && (lastFingerId == -1 || lastFingerId != touch.fingerId))
                {
                    if (touchPad)
                    {
                        if (fadeGUI)
                        {
                            gui.color = new Color(gui.color.r, gui.color.g, gui.color.b, 0.15f);
                        }
                        lastFingerId  = touch.fingerId;
                        fingerDownPos = touch.position;

                        /*
                         * Currently unused.
                         * fingerDownTime = Time.time;
                         */
                    }

                    lastFingerId = touch.fingerId;

                    /* Accumulate taps if it is within the time window */
                    if (tapTimeWindow > 0)
                    {
                        tapCount++;
                    }
                    else
                    {
                        tapCount      = 1;
                        tapTimeWindow = tapTimeDelta;
                    }

                    /* Tell other joysticks we've latched this finger */
                    foreach (Joystick j in joysticks)
                    {
                        if (j == this)
                        {
                            continue;
                        }
                        j.latchedFinger = touch.fingerId;
                    }
                }

                if (lastFingerId == touch.fingerId)
                {
                    /*
                     * Override the tap count with what the iOS SDK reports if it is greater.
                     * This is a workaround, since the iOS SDK does not currently track taps
                     * for multiple touches.
                     */
                    if (touch.tapCount > tapCount)
                    {
                        tapCount = touch.tapCount;
                    }

                    if (touchPad)
                    {
                        /* For a touchpad, let's just set the position directly based on distance from initial touchdown */
                        position = new Vector2
                                   (
                            Mathf.Clamp((touch.position.x - fingerDownPos.x) / (touchZone.width / 2), -1, 1),
                            Mathf.Clamp((touch.position.y - fingerDownPos.y) / (touchZone.height / 2), -1, 1)
                                   );
                    }
                    else
                    {
                        /* Change the location of the joystick graphic to match where the touch is */
                        gui.pixelInset = new Rect
                                         (
                            Mathf.Clamp(guiTouchPos.x, guiBoundary.min.x, guiBoundary.max.x),
                            Mathf.Clamp(guiTouchPos.y, guiBoundary.min.y, guiBoundary.max.y),
                            gui.pixelInset.width,
                            gui.pixelInset.height
                                         );
                    }

                    if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
                    {
                        Restart();
                    }
                }
            }
        }

        if (!touchPad)
        {
            /* Get a value between -1 and 1 based on the joystick graphic location */
            position = new Vector2
                       (
                (gui.pixelInset.x + guiTouchOffset.x - guiCenter.x) / guiTouchOffset.x,
                (gui.pixelInset.y + guiTouchOffset.y - guiCenter.y) / guiTouchOffset.y
                       );
        }

        /* Adjust for dead zone */
        float absoluteX = Mathf.Abs(position.x);
        float absoluteY = Mathf.Abs(position.y);

        if (absoluteX < deadZone.x)
        {
            /* Report the joystick as being at the center if it is within the dead zone */
            position = new Vector2(0, position.y);
        }
        else if (normalize)
        {
            /* Rescale the output after taking the dead zone into account */
            position = new Vector2(Mathf.Sign(position.x) * (absoluteX - deadZone.x) / (1 - deadZone.x), position.y);
        }

        if (absoluteY < deadZone.y)
        {
            /* Report the joystick as being at the center if it is within the dead zone */
            position = new Vector2(position.x, 0);
        }
        else if (normalize)
        {
            /* Rescale the output after taking the dead zone into account */
            position = new Vector2(position.x, Mathf.Sign(position.y) * (absoluteY - deadZone.y) / (1 - deadZone.y));
        }
    }
Beispiel #60
0
    private void HandleInput()
    {
#if UNITY_STANDALONE
        if (Input.GetMouseButtonDown(0))
        {
            lastMouseDownDateTime = System.DateTime.Now;
        }

        if (Input.GetMouseButtonUp(0))
        {
            mouseClickCount++;

            if ((System.DateTime.Now - lastMouseDownDateTime) < mouseClickInterval)
            {
                HandleMouseUp();
            }

            lastMouseUpDateTime = System.DateTime.Now;
        }
        else
        {
            if ((System.DateTime.Now - lastMouseUpDateTime) >= mouseDoubleClickInterval)
            {
                mouseClickCount = 0;
            }
        }
#endif

#if UNITY_ANDROID
        if (Input.touchCount == 1)
        {
            Touch touch = Input.GetTouch(0);

            if (touch.phase == TouchPhase.Began)
            {
                lastMouseDownDateTime = System.DateTime.Now;
            }

            if (touch.phase == TouchPhase.Ended)
            {
                mouseClickCount++;

                if ((System.DateTime.Now - lastMouseDownDateTime) < mouseClickInterval)
                {
                    HandleMouseUp();
                }

                lastMouseUpDateTime = System.DateTime.Now;
            }
            else
            {
                if ((System.DateTime.Now - lastMouseUpDateTime) >= mouseDoubleClickInterval)
                {
                    mouseClickCount = 0;
                }
            }

            //mouseClickCount = Input.GetTouch(0).tapCount;

            //HandleMouseUp();
        }
#endif
    }