Inheritance: MonoBehaviour
示例#1
1
 private void DoClick(object sender, ClickedEventArgs e)
 {
     if (this.teleportOnClick)
     {
         float y = this.reference.position.y;
         Plane plane = new Plane(Vector3.up, -y);
         Ray ray = new Ray(base.transform.position, base.transform.forward);
         bool flag = false;
         float d = 0f;
         if (this.teleportType == SteamVR_Teleporter.TeleportType.TeleportTypeUseCollider)
         {
             TerrainCollider component = Terrain.activeTerrain.GetComponent<TerrainCollider>();
             RaycastHit raycastHit;
             flag = component.Raycast(ray, out raycastHit, 1000f);
             d = raycastHit.distance;
         }
         else if (this.teleportType == SteamVR_Teleporter.TeleportType.TeleportTypeUseCollider)
         {
             RaycastHit raycastHit2;
             Physics.Raycast(ray, out raycastHit2);
             d = raycastHit2.distance;
         }
         else
         {
             flag = plane.Raycast(ray, out d);
         }
         if (flag)
         {
             Vector3 position = ray.origin + ray.direction * d - new Vector3(this.reference.GetChild(0).localPosition.x, 0f, this.reference.GetChild(0).localPosition.z);
             this.reference.position = position;
         }
     }
 }
    void Update()
    {
        if (Input.GetKey(KeyCode.L)) {
            if (!L_downflag) {
                L_downflag=true;
                if (dlight.shadows==LightShadows.None) {
                    dlight.shadows=LightShadows.Soft;
                } else {
                    dlight.shadows=LightShadows.None;
                }
            }
        } else {
            L_downflag=false;
        }

        Material mat=grass.renderer.material;
        Collider col=grass.collider;

        Ray ray = new Ray(rigidbody.position+Vector3.up, -Vector3.up);
        RaycastHit hit=new RaycastHit();
        if (col.Raycast(ray, out hit, 100f)) {
            float dmp=Mathf.Clamp(1-(rigidbody.position.y-0.3042075f)/0.35f,0,1);
            Vector4 pos=new Vector4(hit.textureCoord.x, hit.textureCoord.y, dmp*dmp, 0);
            mat.SetVector("_ballpos", pos);
            rigidbody.drag=dmp*1.0f;
            float v=rigidbody.velocity.magnitude*5.0f;
            dmp/=(v<1) ? 1 : v;
            rigidbody.angularDrag=dmp*1.0f;
        }
    }
示例#3
0
    IEnumerator FireLaser()
    {
        line.enabled = true;

        while(Input.GetButton("Fire1"))
        {
            Ray ray = new Ray(transform.position, new Vector3(1,0,0));
            RaycastHit hit;

            line.SetPosition(0, ray.origin);

            if(Physics.Raycast(ray, out hit, 100))
            {
                Debug.Log("HITITTT!");
                line.SetPosition(1, hit.point);
                if(hit.rigidbody.tag== "Enemy")
                {
                    Destroy(hit.transform.gameObject);
                    Debug.Log("HITITTT!2");
                    hit.rigidbody.AddForceAtPosition(transform.forward* 5, hit.point);
                }
            }
            else
                Debug.Log("NO it!");
                line.SetPosition(1, ray.GetPoint(100));

            yield return null;
        }

        line.enabled = false;
    }
示例#4
0
文件: Gun.cs 项目: LazyGod/1999
    public void Shoot()
    {
        if (CanShoot())
        {
            Ray ray = new Ray(spawn.position, spawn.forward);
            RaycastHit Hit;

            float shootDistance = 20;
            if (Physics.Raycast(ray, out Hit, shootDistance, collisionMask))
            {
                shootDistance = Hit.distance;

                if (Hit.collider.GetComponent<Entity>())
                {
                    Hit.collider.GetComponent<Entity>().TakeDamage(damage);
                }
            }

            nextPossibleShootTime = Time.time + secondsBetweenShoots;

            currentAmmoInMag--;
            Debug.Log(currentAmmoInMag + " / " + totalAmmo);

            audio.Play();

            if (tracer)
            {
                StartCoroutine("RenderTracer", ray.direction * shootDistance);
            }

            Rigidbody newShell = Instantiate(shell, shellEjectionPoint.position, Quaternion.identity) as Rigidbody;
            newShell.AddForce(shellEjectionPoint.forward * Random.Range(150f, 200f) + spawn.forward * Random.Range(-10f, 10f));
        }
    }
示例#5
0
    Transform FindClosestHitObject(Ray ray, out Vector3 hitPoint)
    {
        RaycastHit[] hits = Physics.RaycastAll(ray);

        Transform closestHit = null;
        float distance = 0;
        hitPoint = Vector3.zero;

        foreach(RaycastHit hit in hits) {
            if(hit.transform != this.transform && ( closestHit==null || hit.distance < distance ) ) {
                // We have hit something that is:
                // a) not us
                // b) the first thing we hit (that is not us)
                // c) or, if not b, is at least closer than the previous closest thing

                closestHit = hit.transform;
                distance = hit.distance;
                hitPoint = hit.point;
            }
        }

        // closestHit is now either still null (i.e. we hit nothing) OR it contains the closest thing that is a valid thing to hit

        return closestHit;
    }
    private float origDist; ///< Start distance between camera and lookat-target

    #endregion Fields

    #region Methods

    void FixedUpdate()
    {
        // Camera collision
        Vector3 d = transform.position - m_target.position;
        Ray ray = new Ray();
        float rayDist = d.magnitude;
        ray.direction = d.normalized; // all rays share direction
        // Cast several rays to avoid clipping in corners
        // and to be able to determine ignore-cases(such as small debree)
        numHits = 0;
        for (int x=-rayGridBorderDim;x<rayGridBorderDim+1;x++)
        for (int y=-rayGridBorderDim;y<rayGridBorderDim+1;y++)
        {
            // Create a ray on the grid
            ray.origin = m_target.position + transform.TransformDirection(new Vector3(x,y,0.0f)) * rayGridStepVal;
            if (Physics.Raycast(ray, out hit, rayDist))
            {
                if (hit.distance < closestHitDist)
                {
                    closestHitDist = Mathf.Max(minCamHitAdjustDistance, hit.distance); // camera can not move further than the minimum adjust distance
                    hitOccuredCooldown = 1.0f; // reset cooldown tick
                    numHits++;
                    Debug.DrawLine(ray.origin, ray.origin + ray.direction * hit.distance, Color.white);   // considered ray
                }
                else
                    Debug.DrawLine(ray.origin, ray.origin + ray.direction * hit.distance, Color.yellow);  // non-considered hit ray
            }
            else
                Debug.DrawLine(ray.origin, ray.origin + ray.direction * rayDist, Color.red);              // non hit ray
        }
    }
    void Update () {

        RaycastHit hit;

        //Mouse input
        //Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);


        //VR Input
        Ray ray = new Ray(camTransform.position, camTransform.forward);

        // Perform the raycast and if it hits something on the floor layer...
        if (Physics.Raycast(ray, out hit, shootDistance, objectMask))
        {
            if (hit.transform.GetComponent(typeof(IInteractiveItem)) as IInteractiveItem != null)
            {
                if ((hit.transform.GetComponent(typeof(IInteractiveItem)) as IInteractiveItem).Gazable)
                {
                    if ((interactiveItem = hit.transform.GetComponent<IInteractiveItem>() as IInteractiveItem) != interactiveItem)
                        slider.value = 0f;

                    if (interactiveItem != null && !interactiveItem.Gazed)
                        slider.value += Time.deltaTime / gazeDuration;

                    if (slider.value >= 1f)
                    {
                        interactiveItem.OnGazed();
                        slider.value = 0f;
                    }
                }
            }
            else
            {
                if (interactiveItem != null)
                {
                    slider.value = 0f;
                    interactiveItem.OnEndGazed();
                    interactiveItem = null;
                }
            }

            Debug.Log(hit.transform.gameObject.name);
            //slider.transform.position = new Vector3(0f, 0f, hit.distance);

        }
        else
        {
            slider.value = 0f;
            if (interactiveItem != null)
            {
                interactiveItem.OnEndGazed();
                interactiveItem = null;
            }

            //slider.transform.position = new Vector3(0f, 0f, shootDistance);
            //Debug.Log("Gazing nothing.");
        }


    }
示例#8
0
	bool FindPath(Vector3 target, Vector3 current, List<Vector3> steps, int n) {
		if (n > 100)
			return false;
		if (Vector3.Distance(current, target) < 1f) {
			return true;
		} else {
			List<Node> nodes = new List<Node>();

			for (int i = 0; i < testSteps.Length; i++) {
				Vector3 nextStep = current + testSteps[i] * stepLenght;

				Ray ray = new Ray(nextStep + Vector3.up, Vector3.down);
				RaycastHit hit;
				if (Physics.Raycast(ray, out hit, 1)) {
					Debug.DrawRay(nextStep, Vector3.up, Color.red, 30);
				} else {
					nodes.Add(new Node(Vector3.Distance(nextStep, target), nextStep));
					Debug.DrawRay(nextStep, Vector3.up, Color.green, 30);
				}
			}

			nodes.Sort(delegate(Node a, Node b) {
				return a.distance.CompareTo(b.distance);
			});

			for (int i = 0; i < nodes.Count; i++) {
				bool reachedTarget = FindPath(target, nodes[i].position, steps, n + 1);
				if (reachedTarget)
					steps.Add(target);
			
				return reachedTarget;
			}
		}
		return false;
	}
示例#9
0
    void FixedUpdate()
    {
        //		foreach (GameObject, mouseObject in GameManager.allTheMice, GameManager.alltheMice) {
        for (int i=0; i<GameManager.allTheMice.Count; i++) {

            GameObject mouseTransform = GameManager.allTheMice[i];
            Vector3 directionToMouse = mouseTransform.transform.position - transform.position;
            float angle = Vector3.Angle (directionToMouse, transform.forward);

            if (angle < 90f) {
                Ray catRay = new Ray (transform.position, directionToMouse);
                RaycastHit catRayHitInfo = new RaycastHit ();

                if (Physics.Raycast (catRay, out catRayHitInfo, 30f)) {
                    Debug.DrawRay (catRay.origin, catRay.direction);

                    if (catRayHitInfo.collider.tag == "Mouse") {

                        if (catRayHitInfo.distance < 3f) {
                            GameManager.allTheMice.Remove(mouseTransform);
                            Destroy (mouseTransform);
                            eating.Play();
                        }
                        else {
                            rbodyCat.AddForce (directionToMouse.normalized * 1000f);
                            boss1.Play();
                        }
                    }
                }
            }
        }
    }
示例#10
0
文件: drag.cs 项目: Shipaaaa/TestVuf
 private void MoveTo()
 {
     if (target != lastTarget)
       {
           if ((transform.position - target).sqrMagnitude > heightPlayer + 0.1f)
           {
               if (!walk)
               {
     //              animation.CrossFade(a_Walk.name);
                   walk = true;
               }
               mag = (transform.position - target).magnitude;
               transform.position = Vector3.MoveTowards(transform.position, target, mag > stopStart ? speed * UnityEngine.Time.deltaTime : Mathf.Lerp(speed * 0.5f, speed, mag / stopStart) * UnityEngine.Time.deltaTime);
               ray = new Ray(transform.position, Vector3.up);
               if (Physics.Raycast(ray, out hit, 1000.0f))
               {
                 transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z);
               }
           }
           else
           {
               lastTarget = target;
               if (walk)
               {
     //              animation.CrossFade(a_Idle.name);
                   walk = false;
               }
           }
       }
 }
示例#11
0
    // Update is called once per frame
    void Update()
    {
        if(_draw)
        {

            ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if(unitManager._moveSequence == true && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
            {

            }
            else if(Physics.Raycast(ray,out hit, Mathf.Infinity,layerMask))
            {
                localMousePosition = hit.point;
            }

            distance = (Vector3.Distance(localMousePosition,transform.position)/1000);
            drawLine.gameObject.SetActive(true);
            drawCircle.gameObject.SetActive(true);
            drawGrid.gameObject.SetActive(true);

        }
        else
        {
            drawLine.gameObject.SetActive(false);
            drawCircle.gameObject.SetActive(false);
            drawGrid.gameObject.SetActive(false);
        }
    }
示例#12
0
 // Update is called once per frame
 void Update()
 {
     Ray playerRay = new Ray (transform.position + new Vector3(0f, 30, 0f), transform.forward);
     RaycastHit hit = new RaycastHit();
     if (Physics.Raycast (playerRay, out hit, 100f)) {
         //npcTextPrefab.text = "LOL";
         Debug.DrawRay ( playerRay.origin, playerRay.direction * hit.distance, Color.blue);
         //if the item the raycast is hitting the TV
         if (hit.transform.gameObject.tag == "TV") {
             //if player has object required to interact with TV then...
             if (girlItems.ContainsKey ("Scissors")) {
                 if (Input.GetKeyDown (KeyCode.G)) {
                     Destroy (hit.transform.gameObject);
                     Destroy (transform.Find ("Scissors").gameObject);
                     girlItems.Remove ("Scissors");
                     //Destroy
                 }
             }
         }
         if ( hit.transform.gameObject.tag == "toilet" ) {
             if (girlItems.ContainsKey("Cake")) {
                 if ( Input.GetKeyDown (KeyCode.E) ) {
                     Destroy (hit.transform.gameObject);
                     Destroy (transform.Find ("Cake").gameObject);
                     girlItems.Remove ("Cake");
                 }
             }
         }
     }
 }
    // Update is called once per frame
    void Update()
    {
        // Walking & Straffing Movement
        if (Input.GetButton ("Forward")) {
            transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime);
        }
        if (Input.GetButton ("Back")) {
            transform.Translate(Vector3.back * movementSpeed * Time.deltaTime);
        }
        if (Input.GetButton ("Left")) {
            transform.Translate(Vector3.left * movementSpeed * Time.deltaTime);
        }
        if (Input.GetButton ("Right")) {
            transform.Translate(Vector3.right * movementSpeed * Time.deltaTime);
        }

        // Camera View Movement
        transform.Rotate(Vector3.up, Input.GetAxis ("Mouse X") * viewSensitivity, Space.World);
        playerHead.transform.Rotate(Vector3.left, Input.GetAxis ("Mouse Y") * viewSensitivity, Space.Self);

        // Jump Movement
        Debug.DrawRay(transform.position,Vector3.down);
        if (Input.GetButtonDown ("Jump")){
            Ray ray = new Ray(transform.position, Vector3.down);
            if(Physics.Raycast(ray,1)){
                rigidbody.AddForce(Vector3.up * jumpForce);
            }
        }
    }
示例#14
0
    IEnumerator button()
    {
        RaycastHit hit;
        while (true) {
            mouseRay = transform.parent.camera.ScreenPointToRay(Input.mousePosition);
            Debug.DrawRay (mouseRay.origin, mouseRay.direction*50,Color.blue,1);

            if(Physics.Raycast(mouseRay, out hit,50)){
                if(hit.collider.name == "button"){
                    if(continueButton.gameObject.GetComponent<glow>() == null){
                        continueButton.gameObject.AddComponent<glow>();
                    }
                    onButton = true;
                }
            }else{
                if(continueButton.gameObject.GetComponent<glow>() != null){
                    continueButton.gameObject.GetComponent<glow>().noMore();
                }
                onButton = false;
            }
            if(onButton && canInput){
                if(Input.GetMouseButtonDown(0)){
                    textIndex++;
                }
            }

            continueButton.enabled = canInput;
            if(continueButton.enabled){
                continueButton.transform.Rotate(0,1,0);
            }
            yield return null;
        }
    }
示例#15
0
    // Update is called once per frame
    void Update()
    {
        var ray = new Ray();
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        var hit = new RaycastHit();
        if (Input.GetMouseButtonDown(0))
            if (collider.Raycast(ray, out hit, 100.0f))
            {
                this.startPos = this.parent.transform.position;

                this.timer = 0;
                this.onMove = true;
                this.superScript.updateY((int)Mathf.Abs(_position/7));

            }

        if (this.onMove)
        {
            this.moveOn();
            this.timer += Time.deltaTime * this._speed;
        }
        if (this.timer >= 1) this.onMove = false;

        if (collider.Raycast(ray, out hit, 100.0f))
        {
            Debug.DrawLine(ray.origin, hit.point, Color.green, 1);
          //  texte.material.color = new Color(01 / 255, 47 / 255, 98 / 2);
        }
        else
        {
           // texte.material.color = Color.white;
        }
    }
示例#16
0
        public bool AddBulletAndHit(VanillaCharacter source, Vector3 decalage, VanillaCharacter target)
        {
            Vector3 sourcePoint = source.FeetPosition + (source.Size.y / 2) * Vector3.UNIT_Y + decalage;
            Vector3 targetPoint = target.FeetPosition + target.Size.y / 2 * Vector3.UNIT_Y;
            Vector3 diff = targetPoint - sourcePoint;
            if (Math.Abs(diff.y / Cst.CUBE_SIDE) > 6) { return false; }

            Degree pitch = -Math.ATan2(diff.y,  diff.z);
            Degree yaw = source.GetYaw();
            if (yaw.ValueAngleUnits > 90 && yaw.ValueAngleUnits < 270)
            {
                yaw *= -1;
                yaw += new Degree(180);
            }

            float targetDistance = diff.Length;
            Ray ray = new Ray(sourcePoint + Vector3.NEGATIVE_UNIT_Z, diff.NormalisedCopy);
            float blockDistance = VanillaBlock.getBlockOnRay(source.getIsland(), ray, Bullet.DEFAULT_RANGE, 30);
            if (targetDistance > blockDistance) { return false; }

            SceneNode pitchNode = this.SceneMgr.RootSceneNode.CreateChildSceneNode();
            pitchNode.Position = sourcePoint;
            pitchNode.Pitch(pitch);

            SceneNode yawNode = pitchNode.CreateChildSceneNode();
            yawNode.Yaw(yaw);
            yawNode.AttachObject(StaticRectangle.CreateLine(this.SceneMgr, Vector3.ZERO, new Vector3(0, 0, 15), ColoredMaterials.YELLOW));

            this.mBullets.Add(new Bullet(source, target, pitchNode, yawNode));
            return true;
        }
示例#17
0
 // Update is called once per frame
 void Update()
 {
     //create raycast
     Ray playerRay = new Ray (transform.position, transform.forward);
     RaycastHit hit = new RaycastHit();
     if (Physics.Raycast (playerRay, out hit, 10f)) {
         Debug.DrawRay ( playerRay.origin, playerRay.direction * hit.distance, Color.red);
         if (hit.transform.gameObject.tag == "Throwable2") {
             npcTextPrefab3.text = "Press K to pick scissors up";
             //if player one presses G
             if (holdingObject2 == false && Input.GetKeyDown (KeyCode.K)) {
                 npcTextPrefab3.text = "Press K to throw";
                 guy2.instance.picked2= true;
                 holdingObject2 = true;
                 hit.transform.parent = transform;
             }
             else if (holdingObject2 == true && Input.GetKeyDown (KeyCode.K)) {
                 holdingObject2 = false;
                 guy2.instance.donezo2= true;
                 hit.transform.parent = null;
                 hit.transform.GetComponent<Rigidbody>().constraints &= ~RigidbodyConstraints.FreezePosition;
             }
             hit.transform.GetComponent<Rigidbody>().AddForce (hit.transform.forward * 2000);
         }
         else {
             npcTextPrefab3.text = "";
         }
     }
 }
示例#18
0
文件: Scene.cs 项目: ankitbko/coreclr
 public IEnumerable<ISect> Intersect(Ray r)
 {
     foreach (SceneObject obj in Things)
     {
         yield return obj.Intersect(r);
     }
 }
示例#19
0
    void Shoot(Ray ray, Vector3 gunPosition)
    {
        Vector3 hitPoint;
        RaycastHit info;
        if (Physics.Raycast (ray, out info)) {
            hitPoint = info.point;
            ray = new Ray (gunPosition, hitPoint - gunPosition);
            if (Physics.Raycast (ray, out info)) {
                if (info.collider == null) { return; }
                GameObject obj = info.collider.gameObject;
                hitPoint = info.point;

                var hp = obj.GetComponent<HasHealth> ();

                if (hp != null) {
                    if (info.collider.tag == "Player") {
                        hp.ReceiveDamage (this.damage);
                    }
                } else {
                    if (debrisPrefab != null) {
                        Instantiate (debrisPrefab, hitPoint, Quaternion.identity);
                    }
                }
            } else { return; }
        } else { return; }

        if (bulletTracePrefab != null) {
            var bulletTrace = (GameObject)Instantiate(bulletTracePrefab);
            var lineComponent = bulletTrace.GetComponent<LineRenderer>();
            lineComponent.SetVertexCount(2);
            lineComponent.SetPosition(0, gunPosition);
            lineComponent.SetPosition(1, hitPoint);
        }
    }
示例#20
0
	public void GuiInputClickUp( Ray inputRay)
	{
		if( AttendBonusWindow.Instance != null )
		{
			AttendBonusWindow.Instance.GuiInputClickUp(inputRay);
		}
	}
示例#21
0
 /// <summary>
 /// Load the aim and wait for input to throw BOOMnana
 /// Left clicking outside the valid area will cancel placement of the trap
 /// Right clicking will cancel placement right away
 /// </summary>
 public IEnumerator Boomy(ThrowBoomnana ability)
 {
     distance = ability.distance;
     Activate(true);
     projector.GetComponent<Projector>().material.mainTexture = Resources.Load("Images/AimPointer") as Texture;
     projector.GetComponent<Projector>().aspectRatio = ability.distance / 2;
     while (!Input.GetMouseButtonDown(0) && !Input.GetMouseButtonDown(1))
         yield return new WaitForFixedUpdate();
     if (Input.GetMouseButtonDown(0)) { // Sometimes I haz to press twice TT-TT
         if (isBehind(projector.transform.position - transform.position))
             ability.Cancel();
         else {
             Vector3 me = doNotTouchTerrain(transform.position);
             Ray ray = new Ray(me, (projector.transform.position - me).normalized);
             #region Aim assist
             Transform target = transform;
             RaycastHit hit;
             Ray rayT = GetComponentInChildren<Camera>().ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
             if (Physics.Raycast(rayT, out hit, Mathf.Infinity)) {
                 PlayerStats ps = hit.collider.GetComponent<PlayerStats>();
                 if (ps)
                     target = ps.transform;
             }
             #endregion
             ability.Throw(ray.GetPoint(distance), target);
         //ability.Throw(Vector3.MoveTowards(transform.position, projector.transform.position, distance));
         }
     } else
         ability.Cancel();
     yield return new WaitForFixedUpdate(); // Makes sure you don't activate anything else when you click
     Activate(false);
 }
示例#22
0
    void FixedUpdate()
    {
        cooldownRemaining -= Time.deltaTime;

        var player = GetPlayer();
        if (player == null) { return; }

        var canShoot = false;
        var eyePos = gameObject.transform.position;
        var playerPos = player.transform.position;
        var rayDir = (playerPos - eyePos).normalized;
        RaycastHit hitInfo;
        if (Physics.Raycast (eyePos, rayDir, out hitInfo)) {
            if (hitInfo.collider == player.GetComponent<Collider>()) {
                if (Vector3.Distance(playerPos, eyePos) < maxShootDistance) {
                    canShoot = true;
                }
            }
        }

        if (canShoot && cooldownRemaining <= 0) {
            cooldownRemaining = cooldown;

            var direction = (rayDir + Random.insideUnitSphere * inaccuracy).normalized;
            var gunPosition = gameObject.GetComponent<Collider>().transform.TransformPoint(gunOffset);
            var startPoint = gunPosition + rayDir * 0.1f;
            var ray = new Ray(startPoint, direction);

            Shoot(ray, gunPosition);
        }
    }
示例#23
0
文件: Gun.cs 项目: sybiload/0xyde
	public void Shoot()
	{
		if(CanShoot() && !Pause.pause)
		{
			Ray ray = new Ray(spawn.position,spawn.forward);
			RaycastHit hit;
			Instantiate (smoke, smokespawn.transform.position, spawn.transform.rotation);
			float shotDistance = 20;

			if (Physics.Raycast(ray,out hit, shotDistance))
			{
				shotDistance = hit.distance;
				
				if (hit.collider.tag == "Zombie")
				{
					GameObject go = hit.collider.gameObject;
					mAI other = (mAI)go.GetComponent (typeof(mAI));
					other.hurt();
					Instantiate (blood, hit.transform.position, transform.rotation);
				}
			}

			nextShootTime = Time.time + secondsInterval;

			audio.Play();

			StartCoroutine("RenderTracer", ray.direction * shotDistance);
		}
	}
示例#24
0
    IEnumerator AddRope()
    {
        Ray axis;
        GameObject temp;

        temp = GameObject.CreatePrimitive(PrimitiveType.Capsule);
        temp.transform.localScale = new Vector3 (0.2f, 0.1f, 0.2f);
        temp.AddComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezeRotationY;
        if (rope.Count == 0)
        {
            temp.transform.position = this.transform.position + 10 * Vector3.up;
            temp.transform.rotation = Quaternion.Euler(new Vector3(0, 0, 90));
            rope.Add(temp.transform);
        }
        else if (rope.Count == 1)
        {
            axis = new Ray(rope[rope.Count - 1].position, Vector3.right);
            temp.transform.position = axis.GetPoint (0.1f);
            temp.transform.rotation = Quaternion.Euler(new Vector3(0, 0, 90));
            temp.AddComponent<HingeJoint>().connectedBody = rope[rope.Count - 1].gameObject.rigidbody;
            rope.Add(temp.transform);
        }
        else
        {
            axis = new Ray(rope[rope.Count - 1].position, rope[rope.Count - 1].position - rope[rope.Count - 2].position );
            temp.transform.position = axis.GetPoint (0.1f);
            temp.transform.rotation = rope[rope.Count-1].transform.rotation;
            temp.AddComponent<HingeJoint>().connectedBody = rope[rope.Count - 1].gameObject.rigidbody;
            rope.Add(temp.transform);
        }
        yield return new WaitForSeconds(.01f);
    }
示例#25
0
    //Fixed Update is called every __ seconds, Edit Project Settings Time Fixed TimeStamp
    //Movement
    void FixedUpdate()
    {
        if (Input.GetKey (KeyCode.UpArrow)){
            GetComponent<Rigidbody>().AddForce(GetComponent<Transform>().forward *2f, ForceMode.VelocityChange);
        }

        if (Input.GetKey (KeyCode.LeftArrow)) {
            GetComponent<Rigidbody>().AddForce(GetComponent<Transform>().right *2f, ForceMode.VelocityChange);
            //transform.Rotate(new Vector3(0f,-5f,0f));
        }
        if (Input.GetKey (KeyCode.RightArrow)) {
            GetComponent<Rigidbody>().AddForce(GetComponent<Transform>().right *-2f, ForceMode.VelocityChange);
            //transform.Rotate(new Vector3(0f,5f,0f));
        }

        //transform.position = GetComponent<Transform>
        Ray ray = new Ray (transform.position, -Vector3.up);
        //to know where and what the raycast hit , we have to store that impact info
        RaycastHit rayHit = new RaycastHit (); //Blank Container for Info

        if (Physics.Raycast (ray, out rayHit, 1.1f))
        {
            if (Input.GetKey (KeyCode.RightShift))
            {
                GetComponent<Rigidbody> ().AddForce (new Vector3 (0f, 5000f, 0f), ForceMode.Acceleration);
                Debug.Log (rayHit.point);
                //Destroy (rayHit.collider.gameObject);
            }
        }
    }
示例#26
0
    private void FixedUpdate()
    {
        if(enemy.dead) return;

        // raycasting
        float facing = (transform.localScale.x < 0f ? -1f : 1f);
        Vector2 origin = (Vector2)eye.position + offset*facing;
        Vector2 direction = Vector2.right * transform.localScale.x;
        Ray ray = new Ray(origin, direction);

        RaycastHit2D hit;
        hit = Physics2D.Raycast(ray.origin, ray.direction, visionDistance);
        Debug.DrawRay(ray.origin, ray.direction.normalized * visionDistance, Color.yellow);

        if(hit != null && hit.collider != null) {
            Player player = null;
            if (hit.collider.gameObject.layer == LayerMask.NameToLayer("Player"))
                player = hit.collider.GetComponent<Player>();

            if (hit.collider.gameObject.layer == LayerMask.NameToLayer("Weapon"))
                player = hit.collider.transform.parent.GetComponent<Player>();

                if(player != null)
                    player.Die();
        }
    }
示例#27
0
    // Update is called once per frame
    void FixedUpdate()
    {
        Vector3 directionToMouse = mouse.position - transform.position;
        float angle = Vector3.Angle(transform.forward, directionToMouse);

        if (angle < 90f) {

            Ray catRay = new Ray (transform.position, directionToMouse);
            RaycastHit catRayHitInfo = new RaycastHit();

            if (Physics.Raycast (catRay, out catRayHitInfo, 100f))
            {
                if(catRayHitInfo.collider.tag == "Mouse" )
                {
                    failed.Play();
                    if(catRayHitInfo.distance <= 5)
                {
                        arrow.Play();
                        Destroy (mouse.gameObject);
                }
                    else{

                        rbody.AddForce (directionToMouse.normalized * 1000f);

                    }
                }
            }
        }
    }
    void GroundCheck()
    {
        RaycastHit check;
        Ray downRay = new Ray (transform.position, -transform.up);

        if (Physics.Raycast (downRay, out check)) {
            Debug.DrawLine (transform.position,check.point);
            if (check.distance <= (charCollider.height/2)+.5f)  {
                if (check.collider.tag == "Death"){
                    infoScript.Kill();
                }
                if(check.collider.tag == "win"){
                //	infoScript.camScript.win = true;
                }
                grounded = true;
                groundPos = check;
                frictionCoefficent = initialFrictionCoefficent;
            }else{
                grounded = false;
                frictionCoefficent = airFrictionCoefficent;
            }
        } else{
            frictionCoefficent = airFrictionCoefficent;
            grounded = false;
        }
    }
示例#29
0
    bool checkIfBeingBlocked(Vector3 position)
    {
        //2 rays are needed incase the enemy is inside a collider

        bool forwardCheck = false;
        bool backwardCheck = false;

        Vector3 direction = target.position - position;
        float distance = Mathf.Sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
        distance += 1; //error

        Ray ray = new Ray (position, direction);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, distance, layerMask)) { //send a ray forwards from the enemy
            if (hit.collider.tag == "Player")
                forwardCheck = false;
            else
                forwardCheck = true;
        }

        ray.origin = ray.GetPoint(distance - 1);
        ray.direction = -ray.direction;
        if (Physics.Raycast(ray, out hit, distance, layerMask)) { //send another ray backwards from the player
            if (hit.collider.tag == "Enemy")
                backwardCheck = false;
            else
                backwardCheck = true;
        }

        if (forwardCheck || backwardCheck)
            return true;
        else
            return false;
    }
示例#30
0
    void Update()
    {
        if(Input.GetMouseButtonDown( 0 ))
        {
            if(cam)
            {
                ray = cam.ScreenPointToRay( Input.mousePosition );
            }else{
                ray = Camera.main.ScreenPointToRay( Input.mousePosition );
            }

            RaycastHit rayHit = new RaycastHit();

            if( Physics.Raycast(ray, out rayHit, 100f) )
            {
                if(rayHit.transform.gameObject.layer == 11)
                {
                    rayHit.transform.gameObject.GetComponent<LoadSceneButton>().StartLoading();

                }else if( rayHit.transform.gameObject.layer == 12)
                {
                    rayHit.transform.gameObject.GetComponent<OtherButton>().SetClicked();
                    rayHit.transform.gameObject.GetComponent<OtherButton>().Execute();
                }
            }
        }
    }
    // Update is called once per frame
    void Update()
    {
        //方向ベクトル取得
        Vector3 diff = centerEyesPoint.transform.forward;

        //y軸は回転させない
        diff.y = 0;
        //方向の絶対値が0以上なら
        if (diff.magnitude > 0.01f)
        {
            //自身を回転
            transform.rotation = Quaternion.LookRotation(diff);
        }
        //レイ生成
        Ray ray = new Ray(centerEyesPoint.transform.position, centerEyesPoint.transform.forward);
        //当たったオブジェクト
        RaycastHit hit;

        //視線の先にレイ飛ばす
        if (Physics.Raycast(ray, out hit, 100, layerMask))
        {
            //当たったオブジェクトのタグ
            string tags = hit.transform.tag;
            //タグによって処理変更
            switch (tags)
            {
            //正面の壁を見ている
            case "FRONTWALL":
                //左の壁から爆弾が来てたら
                if (wallController.bombs[(int)WallType.LEFTWALL].Count >= 1)
                {
                    //左側表示
                    leftSerchUI.SetActive(true);
                }
                //来てなければ
                else
                {
                    //左側非表示
                    leftSerchUI.SetActive(false);
                }
                //右の壁から爆弾が来てたら
                if (wallController.bombs[(int)WallType.RIGHTWALL].Count >= 1)
                {
                    //右側表示
                    rightSerchUI.SetActive(true);
                }
                //来てなければ
                else
                {
                    //右側非表示
                    rightSerchUI.SetActive(false);
                }
                break;

            //左の壁を見ている
            case "LEFTWALL":
                //左側非表示
                leftSerchUI.SetActive(false);
                //正面、または右の壁から爆弾が来てたら
                if (wallController.bombs[(int)WallType.RIGHTWALL].Count >= 1 || wallController.bombs[(int)WallType.FRONTWALL].Count >= 1)
                {
                    //右側表示
                    rightSerchUI.SetActive(true);
                }
                //来てなければ
                else
                {
                    //右側非表示
                    rightSerchUI.SetActive(false);
                }
                break;

            //右の壁を見ている
            case "RIGHTWALL":
                //右側非表示
                rightSerchUI.SetActive(false);
                //正面、または左の壁から爆弾が来ていたら
                if (wallController.bombs[(int)WallType.LEFTWALL].Count >= 1 || wallController.bombs[(int)WallType.FRONTWALL].Count >= 1)
                {
                    //左側表示
                    leftSerchUI.SetActive(true);
                }
                //来ていなければ
                else
                {
                    //左側非表示
                    leftSerchUI.SetActive(false);
                }
                break;
            }
        }
        //どこも見ていなければ
        else
        {
            //右側非表示
            rightSerchUI.SetActive(false);
            //左側非表示
            leftSerchUI.SetActive(false);
        }
    }
示例#32
0
    private void Update()
    {
        for (int i = 0; i < hearts.Length; i++)
        {
            if (i < numofhearts)
            {
                hearts[i].enabled = true;
            }
            else
            {
                hearts[i].enabled = false;
            }
        }

        if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began)
        {
            Ray        ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.tag == "d")
                {
                    score         += 1;
                    scoretext.text = score.ToString();
                    crct           = Instantiate(correct, hit.point, Quaternion.identity);
                    Destroy(crct, 0.2f);
                    Destroy(hit.collider.gameObject);
                }
                else if (hit.collider.tag == "b" || hit.collider.tag == "p" || hit.collider.tag == "q")
                {
                    wrng = Instantiate(wrong, hit.point, Quaternion.identity);
                    Handheld.Vibrate();
                    Destroy(wrng, 0.2f);
                    numofhearts -= 1;
                }
            }
        }

        if (score >= 20)
        {
            StartCoroutine(loadwin());
        }

        IEnumerator loadwin()
        {
            yield return(new WaitForSeconds(1f));

            Time.timeScale = 0f;
            ongame.SetActive(false);
            winscreen.SetActive(true);

            int currentlevel = SceneManager.GetActiveScene().buildIndex;

            if (currentlevel - 4 >= PlayerPrefs.GetInt("ALPHABETSLEVELUNLOCKED"))
            {
                PlayerPrefs.SetInt("ALPHABETSLEVELUNLOCKED", (currentlevel - 4) + 1);
                totalscore = PlayerPrefs.GetInt("TOTALSCORE") + 100;
                PlayerPrefs.SetInt("TOTALSCORE", totalscore);
            }
        }

        if (numofhearts <= 0)
        {
            ongame.SetActive(false);
            lossscreen.SetActive(true);
            Time.timeScale = 0f;
        }
    }
示例#33
0
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("space"))
        {
            logText.enabled = !logText.enabled;
        }

        if (Input.GetMouseButtonDown(0))
        {
            Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit rayHit;
            if (Physics.Raycast(ray, out rayHit, 100.0f))
            {
                if (rayHit.collider.tag == "cube")
                {
                    foreach (var cube in all_blocks.all)
                    {
                        if (rayHit.collider.gameObject.transform.position == new Vector3(cube.X, 0, cube.Y))
                        {
                            ressourcesText.text  = "Food : " + cube.nbr_q0;
                            ressourcesText.text += "\nLinemate : " + cube.nbr_q1;
                            ressourcesText.text += "\nDeraumere : " + cube.nbr_q2;
                            ressourcesText.text += "\nSibur : " + cube.nbr_q3;
                            ressourcesText.text += "\nMendiane : " + cube.nbr_q4;
                            ressourcesText.text += "\nPhiras : " + cube.nbr_q5;
                            ressourcesText.text += "\nThystame : " + cube.nbr_q6;
                        }
                    }
                }
                else
                {
                    ressourcesText.text = "";
                }
            }
        }
        t             += Time.deltaTime;
        serverMessage += _server.GetComponent <sceneController>().receivedMessage;
        if (t >= TimeUnit && finish == false)
        {
            t = t % 1f;
            int index = serverMessage.IndexOf('\n');
            if (index == -1)
            {
                return;
            }
            string serverAction = serverMessage.Substring(0, index);
            int    count        = logText.text.Split('\n').Length - 1;
            if (count >= 10)
            {
                logText.text = "";
            }
            logText.text += serverAction + "\n";

            serverMessage = serverMessage.Substring(index + 1);
            string[] tokens = serverAction.Split(' ');
            if (tokens[0] == "msz")
            {
                MSG_MSZ(int.Parse(tokens[1]), int.Parse(tokens[2]));
            }
            if (tokens[0] == "bct")
            {
                MSG_BCT(int.Parse(tokens[1]), int.Parse(tokens[2]), int.Parse(tokens[3]), int.Parse(tokens[4]), int.Parse(tokens[5]), int.Parse(tokens[6]), int.Parse(tokens[7]), int.Parse(tokens[8]), int.Parse(tokens[9]));
            }
            if (tokens[0] == "sgt")
            {
                MSG_SGT(int.Parse(tokens[1]));
            }
            if (tokens[0] == "tna")
            {
                MSG_TNA(tokens[1]);
            }
            if (tokens[0] == "pwn")
            {
                MSG_PWN(int.Parse(tokens[1]), int.Parse(tokens[2]), int.Parse(tokens[3]), int.Parse(tokens[4]), int.Parse(tokens[5]), tokens[6]);
            }
            if (tokens[0] == "ppo")
            {
                MSG_PPO(int.Parse(tokens[1]), int.Parse(tokens[2]), int.Parse(tokens[3]), int.Parse(tokens[4]));
            }
            if (tokens[0] == "pdi")
            {
                MSG_PDI(int.Parse(tokens[1]));
            }
            if (tokens[0] == "pbc")
            {
                MSG_PBC(int.Parse(tokens[1]), serverAction.Substring(5));
            }
            if (tokens[0] == "pgt")
            {
                MSG_PGT(int.Parse(tokens[1]), int.Parse(tokens[2]));
            }
            if (tokens[0] == "pdr")
            {
                MSG_PDR(int.Parse(tokens[1]), int.Parse(tokens[2]));
            }
            if (tokens[0] == "pex")
            {
                MSG_PEX(int.Parse(tokens[1]));
            }
            if (tokens[0] == "pic")
            {
                MSG_PIC(int.Parse(tokens[1]), int.Parse(tokens[2]), int.Parse(tokens[3]), int.Parse(tokens[4]));
            }
            if (tokens[0] == "pie")
            {
                MSG_PIE(int.Parse(tokens[1]), int.Parse(tokens[2]), int.Parse(tokens[3]));
            }
            if (tokens[0] == "pfk")
            {
                MSG_PFK(int.Parse(tokens[1]));
            }
            if (tokens[0] == "eht")
            {
                MSG_EHT(int.Parse(tokens[1]));
            }
            if (tokens[0] == "ebo")
            {
                MSG_EBO(int.Parse(tokens[1]));
            }
            if (tokens[0] == "seg")
            {
                MSG_SEG(tokens[1]);
            }
        }
    }
 public Vector3 GetPoint(Vector3 screenPosition)
 {
     ray = Camera.main.ScreenPointToRay(screenPosition);
     plane.Raycast(ray, out distance);
     return ray.GetPoint(distance);
 }
示例#35
0
    // Update is called once per frame
    void Update()
    {
        if (gameManager.IsGameRunning())
        {
            Ray        ray = cam.ScreenPointToRay(inputManager.GetCursorPosition());
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit))
            {
                transform.position = new Vector3(
                    Mathf.Clamp(hit.point.x, -gameManager.maxDistanceFromCenter, gameManager.maxDistanceFromCenter)
                    , 1, -3.3f);
            }

            if (idleTime > timeDelta)
            {
                idleTime = 0;

                previousPosition = transform.position.x;
            }
            else
            {
                idleTime += Time.deltaTime;
            }

            float movement = transform.position.x - previousPosition;
            speed = Mathf.Abs(movement);

            if (speed > tapSpeed)
            {
                untapDelayLeft = untapDelay;
                direction      = (int)Mathf.Sign(movement);
            }

            if (speed < tapSpeed)
            {
                if (untapDelayLeft < 0)
                {
                    direction = 0;
                }
                else
                {
                    untapDelayLeft -= Time.deltaTime;
                }
            }
            if (speed < maxNoiseSpeed)
            {
                if (untapDelayLeft < 0)
                {
                    direction = 0;
                }
                else
                {
                    untapDelayLeft -= 2 * Time.deltaTime;
                }
            }

            float deltaX = transform.position.x - currentPosition;

            if ((int)Mathf.Sign(deltaX) == direction)
            {
                currentPosition = transform.position.x;
            }
            else
            {
                if (Mathf.Abs(deltaX) > turnDetection)
                {
                    previousPosition = currentPosition;
                    currentPosition  = transform.position.x;
                    direction        = -direction;
                }
            }

            if (direction > 0)
            {
                dollSprite.SetFrame(2);
            }
            else if (direction < 0)
            {
                dollSprite.SetFrame(3);
            }
            else
            {
                dollSprite.SetFrame(1);
            }
        }
    }
示例#36
0
    void Update()
    {
        var playerData = DataManager.Instance.GetPlayerData();

        Vector3 markerXZ = new Vector3(
            marker.position.x,
            transform.position.y,
            marker.position.z);

        if (GetCurrentState() != State.Dead)
        {
            if (playerData.currentHP <= 0)
            {
                SetState(State.Dead);
            }
        }

        if (Input.GetMouseButtonDown(0) == true)
        {
            RaycastHit hitInfo;
            Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hitInfo, rayLength, layerMask))
            {
                //Debug.Log("Picked! " + hitInfo.collider.gameObject);

                if (hitInfo.collider.gameObject.layer == LayerMask.NameToLayer("Enemy"))
                {
                    marker.SetParent(hitInfo.collider.gameObject.transform, false);
                    marker.position = hitInfo.point;
                    SetState(State.AttackRun);
                }
                else if (hitInfo.collider.gameObject.layer == LayerMask.NameToLayer("Board"))
                {
                    marker.SetParent(null);
                    marker.position = hitInfo.point;
                    target          = null;
                    SetState(State.Run);
                }
            }
        }

        if (Vector3.Distance(markerXZ, transform.position) <= 0.01f)
        {
            if (currentState == State.Run)
            {
                SetState(State.Idle);
            }
            return;
        }
        else
        {
            Vector3 dir   = marker.position - transform.position;
            Vector3 dirXZ = new Vector3(dir.x, 0f, dir.z);

            cc.Move(dirXZ.normalized * moveSpeed * Time.deltaTime
                    + Vector3.up * Physics.gravity.y * Time.deltaTime);

            transform.rotation = Quaternion.RotateTowards(
                transform.rotation,
                Quaternion.LookRotation(dirXZ.normalized),
                rotationSpeed * Time.deltaTime);
        }
    }
示例#37
0
    public swipes swipe()
    {
        if (Input.touches.Length > 0)
        {
            Touch t = Input.GetTouch(0);
            if (t.phase == TouchPhase.Began && CrossPlatformInputManager.GetButton("Swipe"))
            {
                firstPressPos = new Vector2(t.position.x, t.position.y);
                animator.StartPlayback();

                Ray        ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
                RaycastHit hit;

                if (Physics.Raycast(ray, out hit))
                {
                    if (hit.collider.gameObject.tag == "Enemy")
                    {
                        detectedObject = hit.collider.gameObject;
                        detectedObject.GetComponent <EnemyController> ().onTap();
                        objectDetected = true;
                        return(swipes.none);
                    }
                    if (hit.collider.gameObject.tag == "Cage")
                    {
                        detectedObject = hit.collider.gameObject;
                        detectedObject.GetComponent <AnimalCageController> ().onTap();
                        objectDetected = true;
                        return(swipes.none);
                    }
                }
            }
            if (t.phase == TouchPhase.Ended)
            {
                secondPressPos = new Vector2(t.position.x, t.position.y);
                currentSwipe   = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
                currentSwipe.Normalize();
                if (currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f)
                {
                    lastswipe = swipes.up;
                    return(swipes.up);
                }
                if (currentSwipe.y < 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f)
                {
                    lastswipe = swipes.down;

                    return(swipes.down);
                }
                if (currentSwipe.x > 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f)
                {
                    lastswipe = swipes.up;
                    return(swipes.right);
                }
                if (currentSwipe.x < 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f)
                {
                    lastswipe = swipes.left;

                    return(swipes.left);
                }
                //only move if havent touched object
                if (objectDetected == false)
                {
                    //print ("tap");
                    return(swipes.tap);
                }

                objectDetected = false;
            }

            return(swipes.none);
        }

        return(swipes.none);
    }
        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))
                {
                    RaycastHit hit;
                    Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                    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;
                        }
                    }
                    //lineRenderer =
                }


                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);
            }
        }
示例#39
0
    void Update_PlayerControlActivation()/*Formally Update_NeighbouringSystem()*/
    {
        #region Neighbouring System
        RaycastHit hitInfo;

        //Sends a ray from the centre of the camera to the point sent into the function and continues
        //in that direction
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        //Checks to see if the ray has hit an object
        //Fills out the hitInfo class as to tell you what collider you hit
        if (Physics.Raycast(ray, out hitInfo) && !EventSystem.current.IsPointerOverGameObject() /*Is used to check to see if mouse is over any UI*/)
        {
            //This is in reference to the Hextile which is inside the GameObject HexTile_0_0
            GameObject currentHitModelObject = hitInfo.collider.transform.gameObject;
            //This is in reference to the Hextiles parent which is HexTile_0_0
            GameObject currentHitParentObject = hitInfo.collider.transform.parent.gameObject;

            //hitInfo.collider.transform.parent.name is done so it gets the name of the object
            //my parnet of my model which was an empty gameobject created so at all times it would be centred
            //Debug.Log("Raycast hit: " + hitInfo.collider.transform.parent.name);
            //Debug.Log("Raycast hit: " + currentHitModelObject.name);

            #region Notes/Thoughts
            //We know what we're mousing over.
            //What if we wanted to show a tooltip or have an
            //action occur

            //WE could could check to see if we're clicking
            #endregion
            //MeshRenderer mr = currentHitModelObject.GetComponentInChildren<MeshRenderer>();
            //Color originalColor = mr.material.color;

            #region attemptToGetCharacter
            GameObject tempHex_GoCharacter = GameObject.Find("group2");
            Color      originalColor       = tempHex_GoCharacter.GetComponentInChildren <MeshRenderer>().material.color;

            if (hitInfo.collider.transform.parent.name == tempHex_GoCharacter.name.ToString())
            {
                Debug.Log(true);
            }



            #endregion

            if (Input.GetMouseButtonDown(0) && hitInfo.collider.transform.parent.name == tempHex_GoCharacter.name.ToString())
            {
                CanvasManagerScript._instance.Activation();
                canvasActivated = true;

                if (!movementActivated)
                {
                    foreach (var unit in MapGeneratorScript.instance.units)
                    {
                        selectedUnit = unit;
                    }

                    GameObject tempHex_go = GameObject.Find("Hex_" + selectedUnit.Hex.C + "_" + selectedUnit.Hex.R);

                    //hexes = tempHex_GoCharacter.GetComponentInParent<UnitScript>().Hex.GetNeighbours(currentHitParentObject, 2, MapGeneratorScript.instance.numColumns, MapGeneratorScript.instance.numRows);
                    //hexes = currentHitParentObject.GetComponent<HexComponentScript>().hex.GetNeighbours(currentHitParentObject, 2, MapGeneratorScript.instance.numColumns, MapGeneratorScript.instance.numRows);
                    hexes = selectedUnit.Hex.GetNeighbours(tempHex_go, 5, MapGeneratorScript.instance.numColumns, MapGeneratorScript.instance.numRows);
                    foreach (HexScript hex in hexes)
                    {
                        GameObject tempHexNeighbour_go = GameObject.Find("Hex_" + hex.C + "_" + hex.R);
                        if (hex.movementCost == 1)
                        {
                            tempHexNeighbour_go.transform.gameObject.GetComponentInChildren <MeshRenderer>().material.color = Color.yellow;
                            if (!selectedHexes.Contains(tempHexNeighbour_go) || selectedHexes == null)
                            {
                                selectedHexes.Add(tempHexNeighbour_go);
                            }
                        }
                    }
                    tempHex_go.GetComponentInChildren <MeshRenderer>().material.color = Color.red;
                }
            }

            else if (/*Input.GetMouseButtonUp(0) && hitInfo.collider.transform.parent.name == tempHex_GoCharacter.name.ToString() || */
                Input.GetKeyDown(KeyCode.Escape))
            {
                CanvasManagerScript._instance.Deactivation();
                canvasActivated = false;

                #region original code for unselection
                //foreach (var unit in MapGeneratorScript.instance.units)
                //{
                //    selectedUnit = unit;
                //}

                //GameObject tempHex_go = GameObject.Find("Hex_" + selectedUnit.Hex.C + "_" + selectedUnit.Hex.R);

                ////hexes = tempHex_GoCharacter.GetComponentInParent<UnitScript>().Hex.GetNeighbours(currentHitParentObject, 2, MapGeneratorScript.instance.numColumns, MapGeneratorScript.instance.numRows);
                ////hexes = currentHitParentObject.GetComponent<HexComponentScript>().hex.GetNeighbours(currentHitParentObject, 2, MapGeneratorScript.instance.numColumns, MapGeneratorScript.instance.numRows);
                //hexes = selectedUnit.Hex.GetNeighbours(tempHex_go, 5, MapGeneratorScript.instance.numColumns, MapGeneratorScript.instance.numRows);
                //foreach (HexScript hex in hexes)
                //{
                //    GameObject tempHexNeighbour_go = GameObject.Find("Hex_" + hex.C + "_" + hex.R);
                //    if (hex.movementCost == 1)
                //        tempHexNeighbour_go.transform.gameObject.GetComponentInChildren<MeshRenderer>().material.color = Color.white;
                //}
                //tempHex_go.GetComponentInChildren<MeshRenderer>().material.color = Color.white;
                #endregion
                foreach (var hex in selectedHexes)
                {
                    hex.transform.gameObject.GetComponentInChildren <MeshRenderer>().material.color = Color.white;
                }
            }
            else
            {
            }
            #endregion
        }
    }
示例#40
0
    void Update_HexSelection()
    {
        if (canvasActivated)
        {
            #region hitDetection
            RaycastHit hitInfo;

            //Sends a ray from the centre of the camera to the point sent into the function and continues
            //in that direction
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            //Checks to see if the ray has hit an object
            //Fills out the hitInfo class as to tell you what collider you hit
            if (Physics.Raycast(ray, out hitInfo) && !EventSystem.current.IsPointerOverGameObject() /*Is used to check to see if mouse is over any UI*/)
            {
                //This is in reference to the Hextile which is inside the GameObject HexTile_0_0
                GameObject currentHitModelObject = hitInfo.collider.transform.gameObject;
                //This is in reference to the Hextiles parent which is HexTile_0_0
                GameObject currentHitParentObject = hitInfo.collider.transform.parent.gameObject;

                //hitInfo.collider.transform.parent.name is done so it gets the name of the object
                //my parnet of my model which was an empty gameobject created so at all times it would be centred
                //Debug.Log("Raycast hit: " + hitInfo.collider.transform.parent.name);
                //Debug.Log("Raycast hit: " + currentHitModelObject.name);

                #region Notes/Thoughts
                //We know what we're mousing over.
                //What if we wanted to show a tooltip or have an
                //action occur

                //WE could could check to see if we're clicking
                #endregion
                //MeshRenderer mr = currentHitModelObject.GetComponentInChildren<MeshRenderer>();
                //Color originalColor = mr.material.color;
                #endregion

                #region attemptToGetCharacter
                GameObject tempHex_GoCharacter = GameObject.Find("group2");
                Color      originalColor       = tempHex_GoCharacter.GetComponentInChildren <MeshRenderer>().material.color;

                if (hitInfo.collider.transform.parent.name == tempHex_GoCharacter.name.ToString())
                {
                    Debug.Log(true);
                }

                #endregion
                foreach (var h in hexes)
                {
                    if (Input.GetMouseButtonDown(0) && hitInfo.collider.transform.parent.name == "Hex_" + h.C + "_" + h.R)
                    {
                        GameObject potentialHexSelection_go = GameObject.Find("Hex_" + h.C + "_" + h.R);
                        potentalSelectedHexColumnPosition = h.C;
                        potentalSelectedHexRowPosition    = h.R;

                        if (h.movementCost == 1)
                        {
                            if (potentialSelectedHexCashe_go != null)
                            {
                                potentialSelectedHexCashe_go.transform.gameObject.GetComponentInChildren <MeshRenderer>().material.color = potentialSelectedHexOriginalColour;
                                potentialSelectedHexOriginalColour = potentialHexSelection_go.transform.gameObject.GetComponentInChildren <MeshRenderer>().material.color;
                                potentialHexSelection_go.transform.gameObject.GetComponentInChildren <MeshRenderer>().material.color = Color.blue;
                                potentialSelectedHexCashe_go = potentialHexSelection_go;
                            }
                            else
                            {
                                potentialSelectedHexOriginalColour = potentialHexSelection_go.transform.gameObject.GetComponentInChildren <MeshRenderer>().material.color;
                                potentialHexSelection_go.transform.gameObject.GetComponentInChildren <MeshRenderer>().material.color = Color.blue;
                                potentialSelectedHexCashe_go = potentialHexSelection_go;
                                potentialHexSelected         = true;
                            }
                        }
                        Debug.Log("It Works");
                    }
                    else if (Input.GetKeyDown(KeyCode.Escape))
                    {
                        potentialSelectedHexCashe_go.transform.gameObject.GetComponentInChildren <MeshRenderer>().material.color = potentialSelectedHexOriginalColour;
                    }
                }
            }
        }
    }
	void CalculatePassengerMovement(Vector3 velocity)
	{
		// The ray being cast
		Ray ray;
		// The hit of a ray
		RaycastHit hit;

		// Stores the passengers on the platform that have already moved
		HashSet<Transform> movedPassengers = new HashSet<Transform>();

		// Initialize the passenger movement list
		passengerMovement = new List<PassengerMovement>();

		// Find the direction the platform is moving
		float directionX = Mathf.Sign(velocity.x);
		float directionY = Mathf.Sign(velocity.y);

		// Vertically moving platform
		if(velocity.y != 0)
		{
			// The size of the ray that will be cast
			float rayLenght = Mathf.Abs(velocity.y) + skinWidth;

			// Creates the RayCast
			for(int i = 0; i < verticalRayCount; i++)
			{
				// Select the origin of the rays based on the moving direction
				Vector2 rayOrigin = (directionY == -1) ? raycastOrigins.bottomLeft : raycastOrigins.topLeft;
				// Adds the spacing to the ray position
				rayOrigin += Vector2.right * (verticalRaySpacing * i);

				// Creates the ray
				ray = new Ray(rayOrigin, Vector2.up * directionY);

				Debug.DrawRay(ray.origin, ray.direction, Color.green);

				// Casts the ray and check the hit
				if(Physics.Raycast(ray, out hit, rayLenght, passengerMask) && hit.distance != 0)
				{
					// Check if not already moved
					if(!movedPassengers.Contains(hit.transform))
					{
						// Adds the passenger to the moved list
						movedPassengers.Add(hit.transform);

						// Calculate the amount the passenger should move
						float pushX = (directionY == 1) ? velocity.x : 0;
						float pushY = velocity.y - (hit.distance - rayLenght) * directionY;
						// Adds the passenger to the to be moved List
						passengerMovement.Add(new PassengerMovement(hit.transform, new Vector3(pushX, pushY), (directionY == 1), true));
					}
				}
			}
		}

		// Horizontally moving Platform
		if(velocity.x != 0)
		{
			// The size of the ray that will be cast
			float rayLenght = 1 + (Mathf.Abs(velocity.x) + skinWidth);

			// Creates the RayCast
			for(int i = 0; i < horizontalRayCount; i++)
			{
				// Select the origin of the rays based on the moving direction
				Vector2 rayOrigin = (directionX == -1) ? raycastOrigins.bottomLeft : raycastOrigins.bottomRight;
				// Adds the spacing to the ray position
				rayOrigin += Vector2.up * (horizontalRaySpacing * i);

				// Creates the ray
				ray = new Ray(rayOrigin, Vector2.right * directionX);

				Debug.DrawRay(ray.origin, ray.direction);

				// Casts the ray and check the hit
				if(Physics.Raycast(ray, out hit, rayLenght, passengerMask) && hit.distance != 0)
				{
					// Check if not already moved
					if(!movedPassengers.Contains(hit.transform))
					{
						// Adds the passenger to the moved list
						movedPassengers.Add(hit.transform);

						// Calculate the amount the passenger should move
						float pushX = velocity.x - (hit.distance - skinWidth) * directionX;
						float pushY = -skinWidth;

						// Adds the passenger to the to be moved List
						passengerMovement.Add(new PassengerMovement(hit.transform, new Vector3(pushX, pushY), false, true));
					}
				}
			}
		}

		//Passenger on horizontally or downward moving platform
		if(directionY == -1 || velocity.y == 0 && velocity.x != 0)
		{
			// The size of the ray that will be cast
			float rayLength = 1 + (skinWidth * 2);

			// Creates the RayCast
			for(int i = 0; i < verticalRayCount; i++)
			{
				// Select the origin of the rays based on the moving direction
				Vector2 rayOrigin = raycastOrigins.topLeft + Vector2.right * (verticalRaySpacing * i);

				// Creates the ray
				ray = new Ray(rayOrigin, Vector2.up);

				Debug.DrawRay(ray.origin, ray.direction);

				// Casts the ray and check the hit
				if(Physics.Raycast(ray, out hit, rayLength, passengerMask) && hit.distance != 0)
				{
					// Check if not already moved
					if(!movedPassengers.Contains(hit.transform))
					{
						// Adds the passenger to the moved list
						movedPassengers.Add(hit.transform);

						// Calculate the amount the passenger should move
						float pushX = velocity.x;
						float pushY = velocity.y;

						// Adds the passenger to the to be moved List
						passengerMovement.Add(new PassengerMovement(hit.transform, new Vector3(pushX, pushY), true, false));
					}
				}
			}
		}
	}
        private void Hero_OnNewPath(Obj_AI_Base hero, GameObjectNewPathEventArgs args)
        {
            if (ObjectCache.menuCache.cache["AutoSetPingOn"].Cast <CheckBox>().CurrentValue == false)
            {
                return;
            }

            if (!hero.IsMe)
            {
                return;
            }

            var path = args.Path;

            if (path.Length > 1 && !args.IsDash)
            {
                var movePos = path.Last().To2D();

                if (checkPing &&
                    lastIssueOrderArgs.Process == true &&
                    lastIssueOrderArgs.Order == GameObjectOrder.MoveTo &&
                    lastIssueOrderArgs.TargetPosition.To2D().Distance(movePos) < 3 &&
                    myHero.Path.Count() == 1 &&
                    args.Path.Count() == 2 &&
                    myHero.IsMoving)
                {
                    //Draw.RenderObjects.Add(new Draw.RenderPosition(myHero.Path.Last().To2D(), 1000));

                    Draw.RenderObjects.Add(new Draw.RenderLine(args.Path.First().To2D(), args.Path.Last().To2D(), 1000));
                    Draw.RenderObjects.Add(new Draw.RenderLine(myHero.Position.To2D(), myHero.Path.Last().To2D(), 1000));

                    //Draw.RenderObjects.Add(new Draw.RenderCircle(lastMoveToServerPos, 1000, System.Drawing.Color.Red, 10));

                    var   distanceTillEnd = myHero.Path.Last().To2D().Distance(myHero.Position.To2D());
                    float moveTimeTillEnd = 1000 * distanceTillEnd / myHero.MoveSpeed;

                    if (moveTimeTillEnd < 500)
                    {
                        return;
                    }

                    var dir1 = (myHero.Path.Last().To2D() - myHero.Position.To2D()).Normalized();
                    var ray1 = new Ray(myHero.Position.SetZ(0), new Vector3(dir1.X, dir1.Y, 0));

                    var dir2 = (args.Path.First().To2D() - args.Path.Last().To2D()).Normalized();
                    var pos2 = new Vector3(args.Path.First().X, args.Path.First().Y, 0);
                    var ray2 = new Ray(args.Path.First().SetZ(0), new Vector3(dir2.X, dir2.Y, 0));

                    Vector3 intersection3;
                    if (ray2.Intersects(ref ray1, out intersection3))
                    {
                        var intersection = intersection3.To2D();

                        var projection = intersection.ProjectOn(myHero.Path.Last().To2D(), myHero.Position.To2D());

                        if (projection.IsOnSegment && dir1.AngleBetween(dir2) > 20 && dir1.AngleBetween(dir2) < 160)
                        {
                            Draw.RenderObjects.Add(new Draw.RenderCircle(intersection, 1000, System.Drawing.Color.Red, 10));

                            var distance = //args.Path.First().To2D().Distance(intersection);
                                           lastMoveToServerPos.Distance(intersection);
                            float moveTime = 1000 * distance / myHero.MoveSpeed;

                            //Console.WriteLine("waa: " + distance);

                            if (moveTime < 1000)
                            {
                                if (numExtraDelayTime > 0)
                                {
                                    sumExtraDelayTime += moveTime;
                                    avgExtraDelayTime  = sumExtraDelayTime / numExtraDelayTime;

                                    pingList.Add(moveTime);
                                }
                                numExtraDelayTime += 1;

                                if (maxExtraDelayTime == 0)
                                {
                                    maxExtraDelayTime = ObjectCache.menuCache.cache["ExtraPingBuffer"].Cast <Slider>().CurrentValue;
                                }

                                if (numExtraDelayTime % 100 == 0)
                                {
                                    pingList.Sort();

                                    var percentile   = ObjectCache.menuCache.cache["AutoSetPercentile"].Cast <Slider>().CurrentValue;
                                    int percentIndex = (int)Math.Floor(pingList.Count() * (percentile / 100f)) - 1;
                                    maxExtraDelayTime = Math.Max(pingList.ElementAt(percentIndex) - Game.Ping, 0);
                                    ObjectCache.menuCache.cache["ExtraPingBuffer"].Cast <Slider>().CurrentValue =
                                        (int)maxExtraDelayTime;

                                    pingList.Clear();

                                    Console.WriteLine("Max Extra Delay: " + maxExtraDelayTime);
                                }

                                Console.WriteLine("Extra Delay: " + Math.Max(moveTime - Game.Ping, 0));
                            }
                        }
                    }
                }

                checkPing = false;
            }
        }
示例#43
0
	static int SphereCastAll(IntPtr L)
	{
		int count = LuaDLL.lua_gettop(L);

		Type[] types1 = {typeof(Ray), typeof(float), typeof(float)};
		Type[] types2 = {typeof(Vector3), typeof(float), typeof(Vector3)};
		Type[] types3 = {typeof(Vector3), typeof(float), typeof(Vector3), typeof(float)};
		Type[] types4 = {typeof(Ray), typeof(float), typeof(float), typeof(int)};

		if (count == 2)
		{
			Ray arg0 = LuaScriptMgr.GetNetObject<Ray>(L, 1);
			float arg1 = (float)LuaScriptMgr.GetNumber(L, 2);
			RaycastHit[] o = Physics.SphereCastAll(arg0,arg1);
			LuaScriptMgr.PushArray(L, o);
			return 1;
		}
		else if (count == 3 && LuaScriptMgr.CheckTypes(L, types1, 1))
		{
			Ray arg0 = LuaScriptMgr.GetNetObject<Ray>(L, 1);
			float arg1 = (float)LuaScriptMgr.GetNumber(L, 2);
			float arg2 = (float)LuaScriptMgr.GetNumber(L, 3);
			RaycastHit[] o = Physics.SphereCastAll(arg0,arg1,arg2);
			LuaScriptMgr.PushArray(L, o);
			return 1;
		}
		else if (count == 3 && LuaScriptMgr.CheckTypes(L, types2, 1))
		{
			Vector3 arg0 = LuaScriptMgr.GetNetObject<Vector3>(L, 1);
			float arg1 = (float)LuaScriptMgr.GetNumber(L, 2);
			Vector3 arg2 = LuaScriptMgr.GetNetObject<Vector3>(L, 3);
			RaycastHit[] o = Physics.SphereCastAll(arg0,arg1,arg2);
			LuaScriptMgr.PushArray(L, o);
			return 1;
		}
		else if (count == 4 && LuaScriptMgr.CheckTypes(L, types3, 1))
		{
			Vector3 arg0 = LuaScriptMgr.GetNetObject<Vector3>(L, 1);
			float arg1 = (float)LuaScriptMgr.GetNumber(L, 2);
			Vector3 arg2 = LuaScriptMgr.GetNetObject<Vector3>(L, 3);
			float arg3 = (float)LuaScriptMgr.GetNumber(L, 4);
			RaycastHit[] o = Physics.SphereCastAll(arg0,arg1,arg2,arg3);
			LuaScriptMgr.PushArray(L, o);
			return 1;
		}
		else if (count == 4 && LuaScriptMgr.CheckTypes(L, types4, 1))
		{
			Ray arg0 = LuaScriptMgr.GetNetObject<Ray>(L, 1);
			float arg1 = (float)LuaScriptMgr.GetNumber(L, 2);
			float arg2 = (float)LuaScriptMgr.GetNumber(L, 3);
			int arg3 = (int)LuaScriptMgr.GetNumber(L, 4);
			RaycastHit[] o = Physics.SphereCastAll(arg0,arg1,arg2,arg3);
			LuaScriptMgr.PushArray(L, o);
			return 1;
		}
		else if (count == 5)
		{
			Vector3 arg0 = LuaScriptMgr.GetNetObject<Vector3>(L, 1);
			float arg1 = (float)LuaScriptMgr.GetNumber(L, 2);
			Vector3 arg2 = LuaScriptMgr.GetNetObject<Vector3>(L, 3);
			float arg3 = (float)LuaScriptMgr.GetNumber(L, 4);
			int arg4 = (int)LuaScriptMgr.GetNumber(L, 5);
			RaycastHit[] o = Physics.SphereCastAll(arg0,arg1,arg2,arg3,arg4);
			LuaScriptMgr.PushArray(L, o);
			return 1;
		}
		else
		{
			LuaDLL.luaL_error(L, "invalid arguments to method: Physics.SphereCastAll");
		}

		return 0;
	}
 public bool IntersectWith(Ray ray, out float distance)
 {
     throw new NotImplementedException();
 }
示例#45
0
    void LateUpdate()
    {
        // Early out if we don't have a target
        if (!target)
        {
            return;
        }

        // Update input and get the last active device
        InputManager.Update();
        var inputDevice = InputManager.ActiveDevice;

        // Only check for input if mouseRotate is true
        if (mouseRotate)
        {
            // Determine which stick to check for input
            InputControl currentStick = (analogStick == ASticks.Left) ? inputDevice.LeftStickX : inputDevice.RightStickX;

            // Check for mouse input first
            if (Input.GetMouseButton((int)mouseButton))
            {
                // Update last cam rotation to stop auto-centering of camera
                lastCamRotation = Time.time;

                // Rotate around target based on mouse movement times the multiplier
                transform.RotateAround(target.position, Vector3.up, Input.GetAxis("Mouse X") * rotationMultiplier * Time.deltaTime);
            }

            // If no mouse input detected, check for analog stick input
            else if ((currentStick.Value != 0 || inputDevice.Analogs[(int)analogStick].Value != 0) && !Input.anyKey)
            {
                // Get movement from the active source (Officially supported controller or not supported)
                float movement = (currentStick.Value != 0) ? -currentStick.Value : -inputDevice.Analogs[(int)analogStick].Value;

                // Update last cam rotation to stop auto-centering of camera
                lastCamRotation = Time.time;

                // Rotate around target based on analog movement times the multiplier
                transform.RotateAround(target.position, Vector3.up, movement * rotationMultiplier * Time.deltaTime);
            }

            else if (Input.GetKey(resetKey) || inputDevice.GetControl(resetButton))
            {
                lastCamRotation = -10.0f;
            }
        }

        // Calculate the current rotation angles (If cam was rotated by mouse within waitTime, keep position)
        float wantedRotationAngle = (Time.time > lastCamRotation + rotationWaitTime) ? target.eulerAngles.y : transform.eulerAngles.y;
        float wantedHeight        = target.position.y + height;

        float currentRotationAngle = transform.eulerAngles.y;
        float currentHeight        = transform.position.y;

        if (camLean)
        {
            // calculate the squared length of the vector from the camera to the target
            float wantedCamDistanceSquared = (wantedHeight - cameraTilt);
            wantedCamDistanceSquared *= wantedCamDistanceSquared;
            wantedCamDistanceSquared  = wantedCamDistanceSquared + distance * distance;

            if (Physics.CheckSphere(transform.position, camCollideRadius))
            {
                // move toward zero distance on x-y from target
                currentDistance = Mathf.Lerp(currentDistance, 0, leanDamping * Time.deltaTime);
            }
            else
            {
                // move toward user defined distance on x-y from target
                currentDistance = Mathf.Lerp(currentDistance, distance, leanDamping * Time.deltaTime);
            }

            // calculate the required height to retain the retain the same camera distance [b = sqrt(h^2 - a^2)]
            wantedHeight = Mathf.Sqrt(wantedCamDistanceSquared - currentDistance * currentDistance) + cameraTilt;
        }

        // Set the position of the camera on the x-z plane to:
        // distance meters behind the target
        transform.position = target.position;

        if (currentDistance > 0)
        {
            // Damp the rotation around the y-axis
            currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);

            // Convert the angle into a rotation
            Quaternion currentRotation = Quaternion.Euler(0f, currentRotationAngle, 0f);

            // rotate vector from target by angle
            transform.position -= currentRotation * Vector3.forward * currentDistance;
        }

        // Damp the height
        currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);

        // Set the height of the camera
        transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);

        // Always look a bit (value of cameraTilt) over the target.
        Vector3 lookAtPt = new Vector3(target.position.x, target.position.y + cameraTilt, target.position.z);

        transform.LookAt(lookAtPt);

        if (camZoom)
        {
            Ray[] frustumRays = new Ray[4];

            frustumRays[0] = transform.camera.ScreenPointToRay(new Vector3(0, 0, 0));
            frustumRays[1] = transform.camera.ScreenPointToRay(new Vector3(transform.camera.pixelWidth, 0, 0));
            frustumRays[2] = transform.camera.ScreenPointToRay(new Vector3(0, transform.camera.pixelHeight, 0));
            frustumRays[3] = transform.camera.ScreenPointToRay(new Vector3(transform.camera.pixelWidth, transform.camera.pixelHeight, 0));

            transform.position = HandleCollisionZoom(transform.position, lookAtPt, minDistance, ref frustumRays);
        }
    }
示例#46
0
	static int Raycast(IntPtr L)
	{
		int count = LuaDLL.lua_gettop(L);

		Type[] types1 = {typeof(Ray), typeof(float)};
		Type[] types2 = {typeof(Ray), typeof(RaycastHit)};
		Type[] types3 = {typeof(Vector3), typeof(Vector3)};
		Type[] types4 = {typeof(Ray), typeof(float), typeof(int)};
		Type[] types5 = {typeof(Vector3), typeof(Vector3), typeof(float)};
		Type[] types6 = {typeof(Ray), typeof(RaycastHit), typeof(float)};
		Type[] types7 = {typeof(Vector3), typeof(Vector3), typeof(RaycastHit)};
		Type[] types8 = {typeof(Vector3), typeof(Vector3), typeof(float), typeof(int)};
		Type[] types9 = {typeof(Vector3), typeof(Vector3), typeof(RaycastHit), typeof(float)};
		Type[] types10 = {typeof(Ray), typeof(RaycastHit), typeof(float), typeof(int)};

		if (count == 1)
		{
			Ray arg0 = LuaScriptMgr.GetNetObject<Ray>(L, 1);
			bool o = Physics.Raycast(arg0);
			LuaScriptMgr.Push(L, o);
			return 1;
		}
		else if (count == 2 && LuaScriptMgr.CheckTypes(L, types1, 1))
		{
			Ray arg0 = LuaScriptMgr.GetNetObject<Ray>(L, 1);
			float arg1 = (float)LuaScriptMgr.GetNumber(L, 2);
			bool o = Physics.Raycast(arg0,arg1);
			LuaScriptMgr.Push(L, o);
			return 1;
		}
		else if (count == 2 && LuaScriptMgr.CheckTypes(L, types2, 1))
		{
			Ray arg0 = LuaScriptMgr.GetNetObject<Ray>(L, 1);
			RaycastHit arg1 = LuaScriptMgr.GetNetObject<RaycastHit>(L, 2);
			bool o = Physics.Raycast(arg0,out arg1);
			LuaScriptMgr.Push(L, o);
			LuaScriptMgr.PushValue(L, arg1);
			return 2;
		}
		else if (count == 2 && LuaScriptMgr.CheckTypes(L, types3, 1))
		{
			Vector3 arg0 = LuaScriptMgr.GetNetObject<Vector3>(L, 1);
			Vector3 arg1 = LuaScriptMgr.GetNetObject<Vector3>(L, 2);
			bool o = Physics.Raycast(arg0,arg1);
			LuaScriptMgr.Push(L, o);
			return 1;
		}
		else if (count == 3 && LuaScriptMgr.CheckTypes(L, types4, 1))
		{
			Ray arg0 = LuaScriptMgr.GetNetObject<Ray>(L, 1);
			float arg1 = (float)LuaScriptMgr.GetNumber(L, 2);
			int arg2 = (int)LuaScriptMgr.GetNumber(L, 3);
			bool o = Physics.Raycast(arg0,arg1,arg2);
			LuaScriptMgr.Push(L, o);
			return 1;
		}
		else if (count == 3 && LuaScriptMgr.CheckTypes(L, types5, 1))
		{
			Vector3 arg0 = LuaScriptMgr.GetNetObject<Vector3>(L, 1);
			Vector3 arg1 = LuaScriptMgr.GetNetObject<Vector3>(L, 2);
			float arg2 = (float)LuaScriptMgr.GetNumber(L, 3);
			bool o = Physics.Raycast(arg0,arg1,arg2);
			LuaScriptMgr.Push(L, o);
			return 1;
		}
		else if (count == 3 && LuaScriptMgr.CheckTypes(L, types6, 1))
		{
			Ray arg0 = LuaScriptMgr.GetNetObject<Ray>(L, 1);
			RaycastHit arg1 = LuaScriptMgr.GetNetObject<RaycastHit>(L, 2);
			float arg2 = (float)LuaScriptMgr.GetNumber(L, 3);
			bool o = Physics.Raycast(arg0,out arg1,arg2);
			LuaScriptMgr.Push(L, o);
			LuaScriptMgr.PushValue(L, arg1);
			return 2;
		}
		else if (count == 3 && LuaScriptMgr.CheckTypes(L, types7, 1))
		{
			Vector3 arg0 = LuaScriptMgr.GetNetObject<Vector3>(L, 1);
			Vector3 arg1 = LuaScriptMgr.GetNetObject<Vector3>(L, 2);
			RaycastHit arg2 = LuaScriptMgr.GetNetObject<RaycastHit>(L, 3);
			bool o = Physics.Raycast(arg0,arg1,out arg2);
			LuaScriptMgr.Push(L, o);
			LuaScriptMgr.PushValue(L, arg2);
			return 2;
		}
		else if (count == 4 && LuaScriptMgr.CheckTypes(L, types8, 1))
		{
			Vector3 arg0 = LuaScriptMgr.GetNetObject<Vector3>(L, 1);
			Vector3 arg1 = LuaScriptMgr.GetNetObject<Vector3>(L, 2);
			float arg2 = (float)LuaScriptMgr.GetNumber(L, 3);
			int arg3 = (int)LuaScriptMgr.GetNumber(L, 4);
			bool o = Physics.Raycast(arg0,arg1,arg2,arg3);
			LuaScriptMgr.Push(L, o);
			return 1;
		}
		else if (count == 4 && LuaScriptMgr.CheckTypes(L, types9, 1))
		{
			Vector3 arg0 = LuaScriptMgr.GetNetObject<Vector3>(L, 1);
			Vector3 arg1 = LuaScriptMgr.GetNetObject<Vector3>(L, 2);
			RaycastHit arg2 = LuaScriptMgr.GetNetObject<RaycastHit>(L, 3);
			float arg3 = (float)LuaScriptMgr.GetNumber(L, 4);
			bool o = Physics.Raycast(arg0,arg1,out arg2,arg3);
			LuaScriptMgr.Push(L, o);
			LuaScriptMgr.PushValue(L, arg2);
			return 2;
		}
		else if (count == 4 && LuaScriptMgr.CheckTypes(L, types10, 1))
		{
			Ray arg0 = LuaScriptMgr.GetNetObject<Ray>(L, 1);
			RaycastHit arg1 = LuaScriptMgr.GetNetObject<RaycastHit>(L, 2);
			float arg2 = (float)LuaScriptMgr.GetNumber(L, 3);
			int arg3 = (int)LuaScriptMgr.GetNumber(L, 4);
			bool o = Physics.Raycast(arg0,out arg1,arg2,arg3);
			LuaScriptMgr.Push(L, o);
			LuaScriptMgr.PushValue(L, arg1);
			return 2;
		}
		else if (count == 5)
		{
			Vector3 arg0 = LuaScriptMgr.GetNetObject<Vector3>(L, 1);
			Vector3 arg1 = LuaScriptMgr.GetNetObject<Vector3>(L, 2);
			RaycastHit arg2 = LuaScriptMgr.GetNetObject<RaycastHit>(L, 3);
			float arg3 = (float)LuaScriptMgr.GetNumber(L, 4);
			int arg4 = (int)LuaScriptMgr.GetNumber(L, 5);
			bool o = Physics.Raycast(arg0,arg1,out arg2,arg3,arg4);
			LuaScriptMgr.Push(L, o);
			LuaScriptMgr.PushValue(L, arg2);
			return 2;
		}
		else
		{
			LuaDLL.luaL_error(L, "invalid arguments to method: Physics.Raycast");
		}

		return 0;
	}
    void InputMessageByMouse()
    {
        RaycastHit hit;
        GameObject hitGO  = null;
        Vector3    hitPos = Vector3.zero;
        Ray        ray    = RayCamera.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit, Mathf.Infinity, CheckLayer.value))
        {
            hitGO  = hit.collider.gameObject;
            hitPos = hit.point;
        }

        //左键点击
        if (Input.GetMouseButtonDown(0))
        {
            if (Time.time - LClickTime < SpaceTime)
            {
                if (BtnClickGO == hitGO)
                {
                    LBtnClickCount++;
                }
                else
                {
                    BtnClickGO     = hitGO;
                    LBtnClickCount = 1;
                }
            }
            else
            {
                BtnClickGO     = hitGO;
                LBtnClickCount = 1;
            }
            if (LBtnClickCount == 1)
            {
                if (LMouseClickCallback != null)
                {
                    LMouseClickCallback(hitGO, hitPos);
                }
            }
            else if (LBtnClickCount == 2)
            {
                if (LMouseDbClickCallback != null)
                {
                    LMouseDbClickCallback(hitGO, hitPos);
                }
            }
            LClickTime = Time.time;
            LDragTime  = LClickTime;
            LStartX    = Input.mousePosition.x;
            LStartY    = Input.mousePosition.y;
        }
        else if (Input.GetMouseButtonDown(1))//右键点击
        {
            if (Time.time - RClickTime < SpaceTime)
            {
                if (BtnClickGO == hitGO)
                {
                    RBtnClickCount++;
                }
                else
                {
                    BtnClickGO     = hitGO;
                    RBtnClickCount = 1;
                }
            }

            else
            {
                BtnClickGO     = hitGO;
                RBtnClickCount = 1;
            }
            if (RBtnClickCount == 1)
            {
                if (RMouseClickCallback != null)
                {
                    RMouseClickCallback(hitGO, hitPos);
                }
            }
            else if (RBtnClickCount == 2)
            {
                if (RMouseDbClickCallback != null)
                {
                    RMouseDbClickCallback(hitGO, hitPos);
                }
            }

            RClickTime = Time.time;
            RDragTime  = RClickTime;
            RStartX    = Input.mousePosition.x;
            RStartY    = Input.mousePosition.y;
        }

        //左键拖拽
        if (LDragTime != -1)
        {
            LEndX = Input.mousePosition.x;
            LEndY = Input.mousePosition.y;
            float minusX = LEndX - LStartX;
            float minusY = LEndY - LStartY;

            if (Mathf.Abs(minusX) > 0 || Mathf.Abs(minusY) > 0)
            {
                if (LMouseDragDeltaCallback != null)
                {
                    LMouseDragDeltaCallback(new Vector2(minusX, minusY));
                }
                if (LMouseDragScreenPosCallback != null)
                {
                    LMouseDragScreenPosCallback(Input.mousePosition);
                }
            }
            LStartX = LEndX;
            LStartY = LEndY;
        }

        //右键拖拽
        if (RDragTime != -1)
        {
            REndX = Input.mousePosition.x;
            REndY = Input.mousePosition.y;
            float minusX = REndX - RStartX;
            float minusY = REndY - RStartY;

            if (Mathf.Abs(minusX) > 0 || Mathf.Abs(minusY) > 0)
            {
                if (RMouseDragDeltaCallback != null)
                {
                    RMouseDragDeltaCallback(new Vector2(minusX, minusY));
                }
                if (RMouseDragScreenPosCallback != null)
                {
                    RMouseDragScreenPosCallback(Input.mousePosition);
                }
            }
            RStartX = REndX;
            RStartY = REndY;
        }

        if (Input.GetMouseButtonUp(0))
        {
            LDragTime = -1;
            if (LMouseUpCallback != null)
            {
                LMouseUpCallback();
            }
        }
        else if (Input.GetMouseButtonUp(1))
        {
            RDragTime = -1;
            if (RMouseUpCallback != null)
            {
                RMouseUpCallback();
            }
        }

        //中间滚轮
        float roll = Input.GetAxis("Mouse ScrollWheel");

        if (roll != 0)
        {
            if (MidMouseScrollCallback != null)
            {
                MidMouseScrollCallback(roll);
            }
        }
        else
        {
            if (LastRoll != 0)
            {
                if (MidMouseScrollEndCallback != null)
                {
                    MidMouseScrollEndCallback();
                }
            }
        }
        LastRoll = roll;

        if (CurGO != hitGO)
        {
            if (hitGO != null)
            {
                if (MouseEnterCallback != null)
                {
                    MouseEnterCallback(hitGO);
                }
                //Debug.Log("enter");
            }

            if (CurGO != null)
            {
                if (MouseExitCallback != null)
                {
                    MouseExitCallback(CurGO);
                }
                //Debug.Log("exit");
            }

            CurGO = hitGO;
        }
    }
    // Update is called once per frame
    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        Vector3 zeroIntersect = ray.origin + ray.direction * (ray.origin.y / -ray.direction.y);

        end.position = zeroIntersect;

        if (Input.GetMouseButtonDown(0))
        {
            mouseDragStart     = Input.mousePosition;
            mouseDragStartTime = Time.realtimeSinceStartup;
        }

        if (Input.GetMouseButtonUp(0))
        {
            Vector2 mouseDragEnd = Input.mousePosition;
            if ((mouseDragEnd - mouseDragStart).sqrMagnitude > 5 * 5 && (Time.realtimeSinceStartup - mouseDragStartTime) > 0.3f)
            {
                //Select

                Rect r = Rect.MinMaxRect(
                    Mathf.Min(mouseDragStart.x, mouseDragEnd.x),
                    Mathf.Min(mouseDragStart.y, mouseDragEnd.y),
                    Mathf.Max(mouseDragStart.x, mouseDragEnd.x),
                    Mathf.Max(mouseDragStart.y, mouseDragEnd.y)
                    );

                RichAI[]      ais = GameObject.FindObjectsOfType(typeof(RichAI)) as RichAI[];
                List <RichAI> ls  = new List <RichAI>();
                for (int i = 0; i < ais.Length; i++)
                {
                    Vector2 p = Camera.main.WorldToScreenPoint(ais[i].transform.position);
                    //p.y = Screen.height - p.y;
                    if (r.Contains(p))
                    {
                        ls.Add(ais[i]);
                    }
                }
                agents = ls.ToArray();
            }
            else
            {
                if (Input.GetKey(KeyCode.LeftShift))
                {
                    multipoints.Add(zeroIntersect);
                }

                if (Input.GetKey(KeyCode.LeftControl))
                {
                    multipoints.Clear();
                }

                if (Input.mousePosition.x > 225)
                {
                    DemoPath();
                }
            }
        }

        if (Input.GetMouseButton(0) && Input.GetKey(KeyCode.LeftAlt) && lastPath.IsDone())
        {
            DemoPath();
        }
    }
示例#49
0
    // Update is called once per frame
    void Update()
    {
        if (Time.time > _nextTick)
        {
            // Set all elements to disappear, they will invert if they are still colliding with cam rays
            foreach (TransparentElement element in _obstacles.Values)
            {
                element.FadingIn = false;
            }

            // Add all elements in cam rays
            List <Transform> obstaclesCollided = new List <Transform>();
            foreach (Transform target in Targets)
            {
                Vector3 direction = target.position - transform.position;
                Ray     ray       = new Ray(transform.position, direction);
                //Debug.DrawRay(transform.position, direction, Color.yellow, (1f / UpdateRate));

                RaycastHit[] hits = Physics.RaycastAll(ray, direction.magnitude - 1, LayerMask);
                foreach (RaycastHit hit in hits)
                {
                    if (!obstaclesCollided.Contains(hit.transform))
                    {
                        obstaclesCollided.Add(hit.transform);
                    }
                }
            }

            // Set fadingIn for all colliding walls
            foreach (Transform obstacleCollided in obstaclesCollided)
            {
                // Add the new colliding wall if not already in the main list
                if (_obstacles.ContainsKey(obstacleCollided))
                {
                    _obstacles[obstacleCollided].FadingIn = true;
                }
                else
                {
                    MeshRenderer renderer = obstacleCollided.GetComponent <MeshRenderer>();
                    if (renderer == null)
                    {
                        Debug.LogWarning("[TRANSPARENT CALLER] Can't find renderer for " + obstacleCollided.name, obstacleCollided);
                        continue;
                    }

                    _obstacles.Add(obstacleCollided, new TransparentElement(renderer.materials, MinAlpha, true));
                }
            }

            // Fade in or out every obstacles
            List <Transform> toRemove = new List <Transform>();
            foreach (KeyValuePair <Transform, TransparentElement> obstacle in _obstacles)
            {
                bool finished = obstacle.Value.Fade((1f / UpdateRate) * FadeSpeed);
                if (obstacle.Value.FadingOut && finished)
                {
                    toRemove.Add(obstacle.Key);
                }
            }

            // Remove all finished fade out
            foreach (Transform toRemoveItem in toRemove)
            {
                _obstacles.Remove(toRemoveItem);
            }

            _nextTick      = Time.time + (1f / UpdateRate);
            ObstaclesFound = _obstacles.Count;
        }
    }
示例#50
0
    public IEnumerator MoveAni()
    {
        int   dir     = -1;
        float minDist = float.MaxValue;

        if (Vector3.SqrMagnitude(target.position - transform.position) > stopDist * stopDist)
        {
            for (int i = 0; i < 4; i++)
            {
                Vector3 checkPos = transform.position + Quaternion.Euler(0, 90 * i, 0) * Vector3.forward;
                Ray     ray      = new Ray(checkPos + Vector3.up * 5, Vector3.down);
                if (!Physics.Raycast(ray, 100, unwalkableMask))
                {
                    float dist = Vector3.SqrMagnitude(target.position - checkPos);
                    if (dist < minDist)
                    {
                        minDist = dist;
                        dir     = i;
                    }
                }
            }
        }

        if (dir != -1)
        {
            float   jumpSpeed = 3.0f;
            Vector3 originPos = HeightZero(transform.position);
            monopolyPosition = HeightZero(transform.position + Quaternion.Euler(0, 90 * dir, 0) * Vector3.forward);

            for (float i = 0; i < 1; i += Time.deltaTime * jumpSpeed)
            {
                transform.localScale = new Vector3(1 + i * 0.15f, 1 - i * 0.2f, 1 + i * 0.15f);
                yield return(null);
            }
            transform.localScale = Vector3.one;

            for (float i = 0; i < 1; i += Time.deltaTime * jumpSpeed)
            {
                transform.position = new Vector3(originPos.x, Mathf.Sin(Mathf.PI * i) * 1.5f, originPos.z) + Quaternion.Euler(0, 90 * dir, 0) * Vector3.forward * i;
                yield return(null);
            }
            transform.position = HeightZero(originPos + Quaternion.Euler(0, 90 * dir, 0) * Vector3.forward);
        }
        else
        {
            float jumpSpeed = 3.0f;
            monopolyPosition = HeightZero(transform.position);
            for (float i = 0; i < 1; i += Time.deltaTime * jumpSpeed)
            {
                transform.localScale = new Vector3(1 + i * 0.15f, 1 - i * 0.2f, 1 + i * 0.15f);
                yield return(null);
            }
            transform.localScale = Vector3.one;

            for (float i = 0; i < 1; i += Time.deltaTime * jumpSpeed)
            {
                transform.position = new Vector3(transform.position.x, Mathf.Sin(Mathf.PI * i) * 1.5f, transform.position.z);
                yield return(null);
            }
            transform.position = HeightZero(transform.position);
        }
    }
示例#51
0
    public override void UpdateInteractable()
    {
        base.UpdateInteractable();

        if (numStep == 0)
        {
            if (!onScales)
            {
                if (Input.touchCount > 0)
                {
                    if (Input.GetTouch(0).phase == TouchPhase.Began)
                    {
                        userTouching = true;
                        Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
                    }
                }

                if (Input.GetMouseButtonDown(0))
                {
                    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                    if (Physics.Raycast(ray))
                    {
                        userTouching = true;
                    }
                }

                if (userTouching)
                {
                    Ray   ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                    float rayDistance;
                    if (interactionPlane.Raycast(ray, out rayDistance))
                    {
                        transform.position = ray.GetPoint(rayDistance);
                        if (transform.position.y < 1.35)
                        {
                            transform.position = new Vector3(transform.position.x, 1.35f, transform.position.z);
                        }
                    }
                }

                if (Input.GetMouseButtonUp(0))
                {
                    userTouching = false;

                    if (transform.position.y >= scales_.transform.position.y &&
                        transform.position.z <= -5.8 && transform.position.z >= -6.2)
                    {
                        Debug.Log("ontop of scales");
                        onScales           = true;
                        transform.position = new Vector3(3.09f, 1.51f, -5.91f);
                        weight             = 12.0f;
                    }
                }
            }

            if (onScales)
            {
                if (Input.GetMouseButtonDown(0))
                {
                    Vector3 buttonPos1 = Camera.main.WorldToScreenPoint(scales_.transform.position + new Vector3(-0.1219f, 0.089f, 0.0689f));
                    Vector3 buttonPos2 = Camera.main.WorldToScreenPoint(scales_.transform.position + new Vector3(-0.1717f, 0.069f, 0.0053f));
                    if (Input.mousePosition.x >= buttonPos1.x && Input.mousePosition.x <= buttonPos2.x &&
                        Input.mousePosition.y >= buttonPos2.y && Input.mousePosition.y <= buttonPos1.y)
                    {
                        weight = 0.0f;
                    }
                }
            }
        }
    }
示例#52
0
    void Update()
    {
        if (preWid != Screen.width || preheight != Screen.height)
        {
            Resources.UnloadUnusedAssets();
            onRESIZED();
        }
        fixALLcamerasPreFrame();
        wheelValue        = UICamera.GetAxis("Mouse ScrollWheel") * 50;
        pointedGameObject = null;
        pointedCollider   = null;
        Ray        line = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(line, out hit, (float)1000, rayFilter))
        {
            pointedGameObject = hit.collider.gameObject;
            pointedCollider   = hit.collider;
        }
        GameObject hoverobject = UICamera.Raycast(Input.mousePosition) ? UICamera.lastHit.collider.gameObject : null;

        if (hoverobject != null)
        {
            if (hoverobject.layer == 11 || pointedGameObject == null)
            {
                pointedGameObject = hoverobject;
                pointedCollider   = UICamera.lastHit.collider;
            }
        }
        InputGetMouseButtonDown_0 = Input.GetMouseButtonDown(0);
        InputGetMouseButtonUp_0   = Input.GetMouseButtonUp(0);
        InputGetMouseButtonDown_1 = Input.GetMouseButtonDown(1);
        InputGetMouseButtonUp_1   = Input.GetMouseButtonUp(1);
        InputEnterDown            = Input.GetKeyDown(KeyCode.Return);
        InputGetMouseButton_0     = Input.GetMouseButton(0);
        for (int i = 0; i < servants.Count; i++)
        {
            servants[i].Update();
        }
        TcpHelper.preFrameFunction();
        delayedTask remove = null;

        while (true)
        {
            remove = null;
            for (int i = 0; i < delayedTasks.Count; i++)
            {
                if (Program.TimePassed() > delayedTasks[i].timeToBeDone)
                {
                    remove = delayedTasks[i];
                    try
                    {
                        remove.act();
                    }
                    catch (System.Exception e)
                    {
                        UnityEngine.Debug.Log(e);
                    }
                    break;
                }
            }
            if (remove != null)
            {
                delayedTasks.Remove(remove);
            }
            else
            {
                break;
            }
        }
    }
    private void SearchForWeapons()
    {
        Vector3 direction = mainCamera.transform.TransformDirection(Vector3.forward); // Looking direction.
        Vector3 origin    = mainCamera.transform.position;                            // Position of the player's head.

        Ray        ray = new Ray(origin, direction);                                  // Creates a ray starting at origin along direction.
        RaycastHit hitInfo;                                                           // Structure used to get information back from a raycast.

        // If the player looks at any nearby weapon (within the range of interaction).
        if (Physics.Raycast(ray, out hitInfo, interactionRange))
        {
            // If the ray hit a gun.
            if (hitInfo.collider.GetComponent <WeaponInfo>() != null)
            {
                // Grab the gun information in the weapons list looking for its id.
                Weapon w = GetWeapon(hitInfo.collider.GetComponent <WeaponInfo>().weaponId);

                // If the weapon exists and the player is not running.
                if (w != null && controller.moveState != MoveState.Running)
                {
                    // If the weapon is not already equipped.
                    if (!isEquipped(w.weaponId))
                    {
                        // If have slot to pick up the weapon.
                        if (weaponEquipped.Count < maxWeapons)
                        {
                            // Displays a message for the player to pick up the weapon.
                            UI.ShowWeaponPickUp(!isEquipped(w.weaponId), w.weaponName);

                            // If press the pick up button.
                            if (Input.GetKeyDown(KeyCode.E) && !isSwitching && ready)
                            {
                                // Adds the weapon to the list of weapons equipped.
                                weaponEquipped.Add(w);

                                // Play the pick up animation.
                                StartCoroutine(Switch(weaponEquipped[currentWeapon], w));

                                // Select the weapon you just picked up.
                                currentWeapon = GetWeaponIndex(w);

                                // If the weapon you picked up must be destroyed by picking up.
                                if (hitInfo.collider.GetComponent <WeaponInfo>().destroyWhenPickup)
                                {
                                    // Destroy the prefab.
                                    Destroy(hitInfo.collider.gameObject);
                                }

                                // Recalculates the weight of the weapons.
                                CalculateWeight();
                            }
                        }
                        else // If you do not have space to get new weapons, then we should change the current weapon.
                        {
                            // Displays a message to the player to change his weapon.
                            UI.ShowWeaponSwitch(true, weaponEquipped[currentWeapon].weaponName, w.weaponName);

                            // If press the pick up button.
                            if (Input.GetKeyDown(KeyCode.E) && !isSwitching && ready)
                            {
                                // Saves the selected weapon, to be instantiated your copy after.
                                Weapon lastWeapon = weaponEquipped[currentWeapon];

                                // Adds the weapon to the list of weapons equipped.
                                weaponEquipped.Add(w);

                                // Call the method to play switch weapon animation.
                                StartCoroutine(Switch(weaponEquipped[currentWeapon], w));

                                // Removes the current weapon from the list of weapons equipped.
                                weaponEquipped.Remove(weaponEquipped[currentWeapon]);

                                // Select the weapon you just picked up.
                                currentWeapon = GetWeaponIndex(w);

                                // Instantiate a prefab clone of the weapon you were equipped with.
                                PickAndDrop(hitInfo.collider.gameObject, lastWeapon);

                                // Recalculates the weight of the weapons.
                                CalculateWeight();
                            }
                        }
                    }
                    else
                    {
                        // Removes pick up or change messages and displays a message saying that the weapon is already selected.
                        UI.ShowWeaponPickUp(false, null);
                        UI.ShowWeaponSwitch(false, null, null);
                        UI.ShowAmmoInfo(w.weaponName + " ALREADY EQUIPPED");
                    }
                }
            }
            else
            {
                // Hide messages.
                UI.ShowWeaponPickUp(false, null);
                UI.ShowWeaponSwitch(false, null, null);
            }
        }
        else
        {
            // Hide messages.
            UI.ShowWeaponPickUp(false, null);
            UI.ShowWeaponSwitch(false, null, null);
        }
    }
示例#54
0
        /// <summary>
        /// The Unity Update() method.
        /// </summary>
        public void Update()
        {
            _UpdateApplicationLifecycle();

            // Hide snackbar when currently tracking at least one plane.
            Session.GetTrackables <DetectedPlane>(m_AllPlanes);
            bool showSearchingUI = true;

            for (int i = 0; i < m_AllPlanes.Count; i++)
            {
                if (m_AllPlanes[i].TrackingState == TrackingState.Tracking)
                {
                    showSearchingUI = false;
                    break;
                }
            }

            SearchingForPlaneUI.SetActive(showSearchingUI);

            // If the player has not touched the screen, we are done with this update.
            Touch touch;

            if (Input.touchCount < 1 || (touch = Input.GetTouch(0)).phase != TouchPhase.Began)
            {
                return;
            }

            //Unity raycast to place poop
            if (EventSystem.current == null || !(EventSystem.current.IsPointerOverGameObject() || EventSystem.current.currentSelectedGameObject != null))
            {
                Ray        ray = FirstPersonCamera.ScreenPointToRay(touch.position);
                RaycastHit rayHit;
                if (Physics.Raycast(ray, out rayHit, 9999f))
                {
                    if (rayHit.transform.gameObject.name != "DetectedPlaneVisualizer(Clone)")
                    {
                        OnUnityPlaneHit(rayHit);
                    }
                    else
                    {
                        Debug.Log(rayHit.transform.gameObject.name);
                        // Raycast against the location the player touched to search for planes.
                        TrackableHit      hit;
                        TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
                                                          TrackableHitFlags.FeaturePointWithSurfaceNormal;

                        if (Frame.Raycast(touch.position.x, touch.position.y, raycastFilter, out hit))
                        {
                            // Use hit pose and camera pose to check if hittest is from the
                            // back of the plane, if it is, no need to create the anchor.
                            if ((hit.Trackable is DetectedPlane) &&
                                Vector3.Dot(FirstPersonCamera.transform.position - hit.Pose.position,
                                            hit.Pose.rotation * Vector3.up) < 0)
                            {
                                Debug.Log("Hit at back of the current DetectedPlane");
                            }
                            else
                            {
                                // Choose the Andy model for the Trackable that got hit.
                                GameObject prefab;
                                if (hit.Trackable is FeaturePoint)
                                {
                                    prefab = AndyPointPrefab;
                                }
                                else
                                {
                                    prefab = AndyPlanePrefab;
                                }

                                // Instantiate Andy model at the hit pose.
                                var andyObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);

                                // Compensate for the hitPose rotation facing away from the raycast (i.e. camera).
                                andyObject.transform.Rotate(0, k_ModelRotation, 0, Space.Self);

                                // Create an anchor to allow ARCore to track the hitpoint as understanding of the physical
                                // world evolves.
                                var anchor = hit.Trackable.CreateAnchor(hit.Pose);

                                // Make Andy model a child of the anchor.
                                andyObject.transform.parent = anchor.transform;
                            }
                        }
                    }
                }
            }
        }
示例#55
0
    void OnEnd(Touch t)
    {
        //Debug.Log(input_state.state);
        Ray        ray = ScreenToRay(t.position);
        RaycastHit hit;

        switch (input_state.state)
        {
        case InputState.State.NODE_SELECT:
            //Node selected : go to menu
            GetComponent <InputManager>().SetState(InputManager.State.MENU_INPUT);
            break;

        case InputState.State.NODE_DRAG:
            //delete node dragged to border
            Vector3 pos = ClampPosition(selection.transform.position);

            bool is_root        = (selection == GetComponent <GameController>().GetRootNode());
            bool drag_to_border = (selection.transform.position - pos).sqrMagnitude > 1e-3;
            if (drag_to_border && !is_root)
            {
                GetComponent <GameController>().RemoveNode(selection);
                selection = null;
            }
            else
            {
                selection.transform.position = pos;
            }
            break;

        case InputState.State.EDGE_DRAG:
            dummy_node.SetActive(false);
            dummy_edge.SetActive(false);

            // avoid raycast hit itself
            selection.GetComponent <ArrowMove>().gameObject.SetActive(false);


            if (Physics.Raycast(ray, out hit))
            {
                GameObject from = dummy_edge.GetComponent <Edge>().origin.gameObject;
                GameObject to   = hit.transform.gameObject;

                if (from != to && isNode(to))
                {
                    GetComponent <GameController>().CreateEdge(from, to);
                }
            }
            else
            {
                GameObject from = dummy_edge.GetComponent <Edge>().origin.gameObject;
                GetComponent <GameController>().CreateEdge(from, dummy_node.transform.position);
            }

            selection.GetComponent <ArrowMove>().MoveToOrigin();
            selection.GetComponent <ArrowMove>().gameObject.SetActive(true);
            dummy_edge.GetComponent <Edge>().origin = null;
            break;

        case InputState.State.SLIDER_DRAG:
            break;

        case InputState.State.DECORATION_DRAG:
            selection.transform.parent.GetComponent <DecorationPallete>().SetLayer(0);
            //Needed to avoid raycast on itself
            dummy_decor.SetActive(false);

            if (Physics.Raycast(ray, out hit))
            {
                GameObject o      = hit.transform.gameObject;
                var        socket = o.GetComponent <DecorationSocket>();
                var        decor  = dummy_decor.GetComponent <Decoration>();
                dummy_decor.layer = 0;
                if (socket != null)
                {
                    if (socket.Set(decor))
                    {
                        dummy_decor.SetActive(true);
                        //Debug.Log(string.Format("Decoration placed({0})!", decor.id));
                    }
                    else
                    {
                        Destroy(dummy_decor);
                    }
                }
                else
                {
                    Destroy(dummy_decor);
                }
            }
            else
            {
                Destroy(dummy_decor);
            }

            //selection.SetActive(true);
            EffectController.GetInstance().Clear();
            break;
        }
        input_state.Clear();
    }
    public IEnumerator PreCast(int EffectNumber)
    {
        if (PrefabsCast[EffectNumber] && TargetMarker)
        {
            //Waiting for confirm or deny
            while (true)
            {
                aim.enabled = false;
                TargetMarker.SetActive(true);
                var forwardCamera = Camera.main.transform.forward;
                forwardCamera.y = 0.0f;
                RaycastHit hit;
                Ray        ray = new Ray(Camera.main.transform.position + new Vector3(0, 2, 0), Camera.main.transform.forward);
                if (Physics.Raycast(ray, out hit, Mathf.Infinity, collidingLayer))
                {
                    TargetMarker.transform.position = hit.point;
                    TargetMarker.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal) * Quaternion.LookRotation(forwardCamera);
                }
                else
                {
                    aim.enabled = true;
                    TargetMarker.SetActive(false);
                }

                if (Input.GetMouseButtonDown(0) && casting == false)
                {
                    aim.enabled = true;
                    TargetMarker.SetActive(false);
                    soundComponentCast = null;
                    if (rotateState == false)
                    {
                        StartCoroutine(RotateToTarget(1, hit.point));
                    }
                    casting = true;
                    PrefabsCast[EffectNumber].transform.position = hit.point;
                    PrefabsCast[EffectNumber].transform.rotation = Quaternion.LookRotation(forwardCamera);
                    PrefabsCast[EffectNumber].transform.parent   = null;
                    currEffect = PrefabsCast[EffectNumber].GetComponent <ParticleSystem>();
                    Effect     = Prefabs[EffectNumber].GetComponent <ParticleSystem>();
                    //Get Audiosource from Prefabs if exist
                    if (Prefabs[EffectNumber].GetComponent <AudioSource>())
                    {
                        soundComponent = Prefabs[EffectNumber].GetComponent <AudioSource>();
                    }
                    //Get Audiosource from PrefabsCast if exist
                    if (PrefabsCast[EffectNumber].GetComponent <AudioSource>())
                    {
                        soundComponentCast = PrefabsCast[EffectNumber].GetComponent <AudioSource>();
                    }
                    StartCoroutine(OnCast(EffectNumber));
                    StartCoroutine(Attack(EffectNumber));
                    //Use ult after main skill
                    if (UltimatePrefab[EffectNumber] != null)
                    {
                        StartCoroutine(Ult(EffectNumber, 0.5f, castingTime[EffectNumber], hit.point, Quaternion.LookRotation(forwardCamera), true));
                    }
                    yield break;
                }
                else if (Input.GetMouseButtonDown(1))
                {
                    aim.enabled = true;
                    TargetMarker.SetActive(false);
                    yield break;
                }
                yield return(null);
            }
        }
        else if (casting == false)
        {
            Effect = Prefabs[EffectNumber].GetComponent <ParticleSystem>();
            ////Get Audiosource from prefab if exist
            if (Prefabs[EffectNumber].GetComponent <AudioSource>())
            {
                soundComponent = Prefabs[EffectNumber].GetComponent <AudioSource>();
            }
            casting = true;
            StartCoroutine(Attack(EffectNumber));
            yield break;
        }
        else
        {
            yield break;
        }
    }
示例#57
0
 /// <summary>
 /// Returns a distance to the closest point on the ray
 /// </summary>
 public static float PointRay(Vector3 point, Ray ray)
 {
     return(point.DistanceTo(Closest.PointRay(point, ray)));
 }
 /// <summary>
 /// Tests a ray against the entry.
 /// </summary>
 /// <param name="ray">Ray to test.</param>
 /// <param name="maximumLength">Maximum length, in units of the ray's direction's length, to test.</param>
 /// <param name="rayHit">Hit location of the ray on the entry, if any.</param>
 /// <returns>Whether or not the ray hit the entry.</returns>
 public override bool RayCast(Ray ray, float maximumLength, out RayHit rayHit)
 {
     return(Shape.RayCast(ref ray, maximumLength, ref worldTransform, out rayHit));
 }
示例#59
0
 /// <summary>
 /// Returns the distance between the closest points on the ray and the sphere
 /// </summary>
 public static float RaySphere(Ray ray, Sphere sphere)
 {
     return(RaySphere(ray.origin, ray.direction, sphere.center, sphere.radius));
 }
示例#60
0
    // Update is called once per frame
    void Update()
    {
        //UnityEngine.Touch[] myTouches = Input.touches;

        tCount.text = Input.touchCount.ToString();

        if (Input.touchCount > 0 && Input.touchCount < 2)
        {
            if (Input.GetTouch(0).phase == TouchPhase.Began)
            {
                Ray        mouseRay = GenerateMouseRay(Input.GetTouch(0).position);
                RaycastHit hit;

                if (Physics.Raycast(mouseRay.origin, mouseRay.direction, out hit))
                {
                    objPlane = new Plane(Camera.main.transform.forward * -1, laser1.transform.position);


                    //calc touch offset
                    Ray   mRay = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
                    float rayDistance;
                    objPlane.Raycast(mRay, out rayDistance);
                    laser1.transform.position = Vector3.Lerp(transform.position, hit.point, Time.time);
                    mO = laser1.transform.position - mRay.GetPoint(rayDistance);
                }
            }
            else if (Input.GetTouch(0).phase == TouchPhase.Moved)
            {
                Ray   mRay = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
                float rayDistance;
                if (objPlane.Raycast(mRay, out rayDistance))
                {
                    laser1.transform.position = mRay.GetPoint(rayDistance) + mO;
                }
            }

            else if (Input.GetTouch(0).phase == TouchPhase.Ended)
            {
                linerenderer.enabled = false;
            }
        }

        if (Input.touchCount > 1)
        {
            if (Input.GetTouch(1).phase == TouchPhase.Began)
            {
                linerenderer.enabled = true;

                //Draw touch ray?
                Ray        mouseRay = GenerateMouseRay(Input.GetTouch(1).position);
                RaycastHit hit;

                if (Physics.Raycast(mouseRay.origin, mouseRay.direction, out hit))
                {
                    objPlane = new Plane(Camera.main.transform.forward * -1, laser2.transform.position);


                    //calc touch offset
                    Ray   mRay = Camera.main.ScreenPointToRay(Input.GetTouch(1).position);
                    float rayDistance;
                    objPlane.Raycast(mRay, out rayDistance);
                    laser2.transform.position = Vector3.Lerp(transform.position, hit.point, Time.time);
                    m1 = laser2.transform.position - mRay.GetPoint(rayDistance);
                }
            }
            else if (Input.GetTouch(1).phase == TouchPhase.Moved)
            {
                Ray   mRay = Camera.main.ScreenPointToRay(Input.GetTouch(1).position);
                float rayDistance;
                if (objPlane.Raycast(mRay, out rayDistance))
                {
                    laser2.transform.position = mRay.GetPoint(rayDistance) + m1;
                }
            }
            else if (Input.GetTouch(1).phase == TouchPhase.Ended)
            {
                linerenderer.enabled = false;
            }
        }

        if (linerenderer.enabled == true)
        {
            Vector3    raycastDir = laser2.transform.position - laser1.transform.position;
            Ray        laserRay   = new Ray(laser1.transform.position, raycastDir);
            RaycastHit hit1;
            Debug.DrawRay(laser1.transform.position, raycastDir);
            if (Physics.Raycast(laserRay.origin, laserRay.direction, out hit1))
            {
                print(hit1.collider.gameObject.name);
                enemy.GetComponent <EnemyHealth>().enemyHealth -= 1;
            }
        }
    }