Exemplo n.º 1
0
    public void BuildFace(ModelData data, Vector3 start, Vector3 offset1, Vector3 offset2)
    {
        int index = data.verts.Count;

        Vector3 scale = GetScale();
        start.Scale(scale);
        offset1.Scale(scale);
        offset2.Scale(scale);

        if (IsCentered())
        {
            Vector3 o = data.offset;
            o.Scale(scale);
            start -= o;
        }

        data.verts.Add(start);
        data.verts.Add(start + offset1);
        data.verts.Add(start + offset2);
        data.verts.Add(start + offset1 + offset2);

        data.tris.Add(index + 0);
        data.tris.Add(index + 1);
        data.tris.Add(index + 2);
        data.tris.Add(index + 3);
        data.tris.Add(index + 2);
        data.tris.Add(index + 1);
    }
Exemplo n.º 2
0
    public IEnumerator ChooseDestination(float time, Vector3 faceDirection)
    {
        yield return new WaitForSeconds(time);

        isMoving = true;

        faceDirection.Scale(new Vector3(Random.Range(-1.0f, 1.0f), 0, Random.Range(-1.0f, 1.0f)));

        if (gameObject == alphaLeader) {
            faceDirection *= Random.Range(30, 200);
            destination = transform.position + faceDirection;
        }  else {
            faceDirection *= Random.Range(30, 100);
            destination = alphaLeader.transform.position + faceDirection;
        }

        NavMeshHit hit;

        if (NavMesh.SamplePosition(destination, out hit, 100, 1)) {
            destination = hit.position;
            agent.SetDestination(destination);

            //CreateDestinationSphere(destination);
        }
    }
Exemplo n.º 3
0
 // Update is called once per frame
 void Update()
 {
     transform.Rotate (move, Time.deltaTime * speed);
     counter++;
     if (counter > change_dir) {
         counter = 0;
         dir = (dir + 1) % 7;
     }
     switch (dir){
     case 0:
         dir_ = Vector3.right;
         break;
     case 1:
         dir_ = Vector3.forward;
         break;
     case 2:
         dir_= Vector3.left;
         break;
     case 3:
         dir_ = Vector3.back;
         break;
     case 4:
         dir_ = Vector3.up;
         break;
     case 5:
         dir_= Vector3.right;
         break;
     case 6:
         dir_ = Vector3.down;
         break;
     }
     dir_.Scale (scaler);
     move = move + dir_;
     move = move.normalized;
 }
Exemplo n.º 4
0
    // Update is called once per frame
    void Update()
    {
        amp.x = Screen.width;

        float num = splitNum;
        float d = 1.0f / num;

        d = Mathf.Clamp01(d);

        graphics.Clear();

        for(int i = 0; i < num+1; i++){
            float x = d * i;
            float y = curve.Evaluate(x);

            Vector3 pos = new Vector3(x,y,0);
            pos.Scale(amp);

            Color c = Color.Lerp(Color.black, color, x);

            if(i == 0){
                graphics.MoveTo(pos, c, thickness);
            }else{
                graphics.LineTo(pos, c, thickness);
            }
        }
        graphics.Render();
    }
Exemplo n.º 5
0
    public float maxXForceFraction; // = 2

    IEnumerator SpawnTarget()
    {
        while (true)
        {
            yield return new WaitForSeconds(Random.Range(minSpawnTime, maxSpawnTime));
            if (Target != null)
            {
                GameObject curr = (GameObject)Instantiate(
                    Target,
                    new Vector3(Random.Range(-150, 150), -100, 0),
                    Quaternion.identity
                );
                Vector3 force = new Vector3();
                force.x = curr.transform.position.x <= 0.0f ? 1 : -1;
                force.x *= Random.Range(minXForceFraction, maxYForceFraction);
                force.y = Random.Range(minYForceFraction, maxXForceFraction);
                force.z = 0;
                force.Scale(forceScale);

                Rigidbody rb = curr.GetComponent<Rigidbody>();
                rb.AddForce(force, ForceMode.Impulse);
                rb.angularVelocity = new Vector3(0,0,Random.Range(-150, 150));
            }
        }
    }
Exemplo n.º 6
0
    void translate(Vector3 delta)
    {
        Vector3 newPos = transform.position;
        delta.Scale(parallaxFactor);
        newPos = basePlanePos - delta;

        transform.position = newPos;
    }
Exemplo n.º 7
0
 //-------------------------------------------------------------------------
 public void MoveTo(Vector2 pos, float speed)
 {
     Vector3 currPos = this.transform.position;
     velocity_ = new Vector3(pos.x, pos.y, currPos.z) - currPos;
     velocity_.Normalize();
     velocity_.Scale(new Vector3(speed, speed, speed));
     dest_ = new Vector3(pos.x, pos.y, currPos.z);
     isMoving_ = true;
 }
    void LateUpdate()
    {
        oldPos = transform.position;
        if (BuildTypeData.buildType == BuildType.VITA&&!Input.GetMouseButton(0)){
            if ((Input.GetAxisRaw("RHorizontal") > 0.1f || Input.GetAxis("RHorizontal") < -0.1f) ||
                Input.GetAxisRaw("RVertical") > 0.1f || Input.GetAxis("RVertical") < -0.1f){
                Vector3 inputRightStick = new Vector3(Input.GetAxisRaw("RHorizontal"), Input.GetAxisRaw("RVertical"), 0);
                inputRightStick.Scale(new Vector3(( camSizeInUnity / 5f), -((camSizeInUnity / 6f)*0.5625f),0));
                targetPos = (cameraTarget.transform.position + inputRightStick);
            }else{
                targetPos = cameraTarget.transform.position;
            }
        }else{
            //get input and mouse position
            Vector3 mouseScreenPos = Input.mousePosition;
            int screenWidth = Screen.width;
            int screenHeight = Screen.height;
            if (mouseScreenPos.x < 0) {
                mouseScreenPos.x = 0;
            }
            else if (mouseScreenPos.x > screenWidth){
                mouseScreenPos.x = screenWidth;
            }
            if (mouseScreenPos.y < 0) {
                mouseScreenPos.y = 0;
            }
            else if (mouseScreenPos.y > screenHeight){
                mouseScreenPos.y = screenHeight;
            }
            Ray mouseRay = Camera.main.ScreenPointToRay(mouseScreenPos);
            Vector3 mousePosition = new Vector3(mouseRay.origin.x, mouseRay.origin.y, 0);
            Vector2 mousePos2D = new Vector2(mouseRay.origin.x, mouseRay.origin.y);
            Vector3 distMouseTarget = mousePosition - cameraTarget.transform.position;
            targetPos = (cameraTarget.transform.position + (distMouseTarget / 3));
        }

        if (cameraFollowX)	{
            newXPos = Mathf.SmoothDamp(oldPos.x, targetPos.x, ref velocity.x, smoothTime);
        }
        if (cameraFollowY){
            newYPos = Mathf.SmoothDamp(oldPos.y, targetPos.y, ref velocity.y, smoothTime);
        }
        if(newXPos>maxXpos){
            newXPos = maxXpos;
        }else if(newXPos<minXpos){
            newXPos = minXpos;
        }
        if(newYPos>maxYpos){
            newYPos = maxYpos;
        }else if(newYPos<minYpos){
            newYPos = minYpos;
        }
        //Update camera position
        newPos = new Vector3(newXPos,newYPos,oldPos.z);
        transform.position = newPos;
    }
 private Vector3 ComputeAverageRotation(List<Vector3> rotations)
 {
     Vector3 avg = new Vector3();
     foreach (var rot in rotations)
     {
         avg += rot;
     }
     var scaling = new Vector3(1f / rotations.Count, 1f / rotations.Count, 1f / rotations.Count);
     avg.Scale(scaling);
     return avg;
 }
Exemplo n.º 10
0
 /// <summary>
 /// Performs the move.
 /// </summary>
 protected virtual void performMove()
 {
     timesIncremented = 0;
     Tile.Map.moveActor(this.gameObject, _path[0].Location);
     Vector3 pos = transform.position;
     Vector3 goalPos = Tile.transform.position;
     velocity = new Vector3(goalPos.x-pos.x, 0, goalPos.z - pos.z);
     transform.LookAt(new Vector3(goalPos.x, pos.y, goalPos.z));
     velocity.Scale(new Vector3(1/(float)NumberOfIncrements, 0, 1/(float)NumberOfIncrements));
     _path.RemoveAt(0);
 }
Exemplo n.º 11
0
 //calibrate rubber bands once
 void calibrateRubberBand()
 {
     rubberBand = GetComponentInParent<LineRenderer> ();
     orthogonalSideOffset = Vector3.Cross (-transform.position, Vector3.up);
     orthogonalSideOffset.Normalize ();
     orthogonalSideOffset.Scale (new Vector3 (0.4f, 0.4f, 0.4f));
     rubberBand.SetPosition (0, transform.position + orthogonalSideOffset);
     rubberBand.SetPosition (1, transform.position + orthogonalSideOffset/2);
     rubberBand.SetPosition (2, transform.position - orthogonalSideOffset/2);
     rubberBand.SetPosition (3, transform.position - orthogonalSideOffset);
     updateRubberBand ();
 }
Exemplo n.º 12
0
    public void SetGrid0()
    {
        List<GameObject> out_list = new List<GameObject>();
        Vector3 pos = plane_list[0].transform.position;

        terrainGen.GetComponent<ProceduralToolkit.Examples.UI.LowPolyTerrainGeneratorUI>().SendPlane(plane_list[2]);
        terrainGen.GetComponent<ProceduralToolkit.Examples.UI.LowPolyTerrainGeneratorUI>().SendPlane(plane_list[5]);
        terrainGen.GetComponent<ProceduralToolkit.Examples.UI.LowPolyTerrainGeneratorUI>().SendPlane(plane_list[8]);
        terrainGen.GetComponent<ProceduralToolkit.Examples.UI.LowPolyTerrainGeneratorUI>().SendPlane(plane_list[7]);
        terrainGen.GetComponent<ProceduralToolkit.Examples.UI.LowPolyTerrainGeneratorUI>().SendPlane(plane_list[6]);

        plane_list[8] = plane_list[4];
        plane_list[4] = plane_list[0];
        plane_list[5] = plane_list[1];
        plane_list[7] = plane_list[3];

        Vector3 dist0 = new Vector3(size_x, 0, size_z);
        Vector3 dist1 = new Vector3(size_x, 0, size_z);
        Vector3 dist2 = new Vector3(size_x, 0, size_z);
        Vector3 dist3 = new Vector3(size_x, 0, size_z);
        Vector3 dist4 = new Vector3(size_x, 0, size_z);
        dist0.Scale(dir_list[(int)directions.NE]);
        dist1.Scale(dir_list[(int)directions.EAST]);
        dist2.Scale(dir_list[(int)directions.SE]);
        dist3.Scale(dir_list[(int)directions.SOUTH]);
        dist4.Scale(dir_list[(int)directions.SW]);

        plane_list[6] = SpawnPlane(pos + dist0);
        plane_list[3] = SpawnPlane(pos + dist1);
        plane_list[0] = SpawnPlane(pos + dist2);
        plane_list[1] = SpawnPlane(pos + dist3);
        plane_list[2] = SpawnPlane(pos + dist4);
        renamePlanes();

        StitchRight(plane_list[7], plane_list[6]);
        StitchRight(plane_list[4], plane_list[3]);
        StitchRight(plane_list[1], plane_list[0]);
        StitchRight(plane_list[2], plane_list[1]);

        StitchDown(plane_list[6], plane_list[3]);
        StitchDown(plane_list[3], plane_list[0]);
        StitchDown(plane_list[4], plane_list[1]);
        StitchDown(plane_list[5], plane_list[2]);

        UpdatePlane(plane_list[7]);
        UpdatePlane(plane_list[4]);
        UpdatePlane(plane_list[1]);
        UpdatePlane(plane_list[2]);
        UpdatePlane(plane_list[6]);
        UpdatePlane(plane_list[3]);
        UpdatePlane(plane_list[5]);
    }
Exemplo n.º 13
0
    public Vector3 GetAverageVelocity()
    {
        Vector3 averageVelocity = new Vector3();

        foreach (Transform t in transform) {
            averageVelocity += t.forward * (t.GetComponent<Boid>().maxSpeed+0.1f);
        }

        int count = transform.childCount;
        averageVelocity.Scale(new Vector3(1.0f/count, 1.0f/count, 1.0f/count));

        return averageVelocity;
    }
Exemplo n.º 14
0
    public Vector3 GetAveragePosition()
    {
        Vector3 averagePosition = new Vector3();

        foreach (Transform t in transform) {
            averagePosition += t.position;
        }

        int count = transform.childCount;
        averagePosition.Scale(new Vector3(1.0f/count, 1.0f/count, 1.0f/count));

        return averagePosition;
    }
Exemplo n.º 15
0
    public override Vector3 GetPosition(MBParticle PT)
    {
        float r = Random.Range(Hollow, 1);
        float l = -Random.Range(0, Mathf.PI * 2);
        float h = Random.Range(-Mathf.PI/2+Arc*Mathf.PI/2, Mathf.PI / 2);
        float ch = Mathf.Cos(h);
        Vector3 v = new Vector3(r * Mathf.Cos(l) * ch,
                                r * Mathf.Sin(h),
                                  r * Mathf.Sin(l) * ch);
        v.Scale(Scale);

        return v;
    }
Exemplo n.º 16
0
	//MIO TODO: This his written in a hurry. Rewrite the smart way
	public void SpawnScore(Vector3 position, int value) {
		Transform scorePrefabTransform = (Instantiate(scorePrefab, position, Quaternion.identity) as GameObject).transform;
		scorePrefabTransform.parent = transform;

		finalPosition = gameCamera.WorldToViewportPoint(position);
		finalPosition = scoreCamera.ViewportToWorldPoint(finalPosition);
		finalPosition.Scale(worldCoordScaleFactor);
		
		scorePrefabTransform.position = finalPosition;
		scorePrefabTransform.localScale = new Vector3(textSize, textSize, 1);
		
		UILabel scoreUILabel = scorePrefabTransform.GetComponentInChildren<UILabel>();
		scoreUILabel.text = value.ToString();
		
		Destroy(scorePrefabTransform.gameObject, scorePrefabTransform.animation.clip.length);
	}
Exemplo n.º 17
0
    // Update is called once per frame
    void Update()
    {
        //randomly spawn enemies
        if (Random.value < spawnChance){
            Vector3 spawnTrans = new Vector3 (Random.Range(-.5f,.5f),Random.Range(-.5f,.5f),Random.Range(-.5f,.5f));
            spawnTrans.Scale(spawnArea);
            int randomIndex = Random.Range(0,enemySpawns.Length);
            Vector3 pos = enemySpawns[randomIndex].transform.position;
            //spawn enemy and put it in the right spot
            Enemy e = (Enemy)Instantiate(enemyPrefab);
            e.transform.position = pos + spawnTrans;

            //parent to us (the spawner) so that this object can receive messages on death
            e.transform.parent = transform;
        }
    }
Exemplo n.º 18
0
    //public bool derp;
    //public Vector3 thevec;
    //public Color color;
    //public AnimationCurve curve;
    //public Gradient gradient;
    // Use this for initialization
    //void Start () {
    //
    //}
    // Update is called once per frame
    void Update()
    {
        //Randomly spawn robot enemies
        if(Random.value < spawnChance){
            //choose position in a volume centered around local origin
            Vector3 pos = new Vector3(Random.Range(-0.5f, 0.5f),Random.Range(-0.5f, 0.5f),Random.Range(-0.5f, 0.5f));
            pos.Scale (spawnArea);

            //spawn!
            GameObject go = (GameObject)Instantiate (enemyPrefab);
            go.transform.position = pos + transform.position;

            //parent newly instantiated thing to "me" (spawnPoint)
            go.transform.parent = transform;
        }
    }
Exemplo n.º 19
0
    public override Vector3 CalculateSteering(Vector3 pos)
    {
        Vector3 steering = new Vector3();

        // Calculate steering
        if (targetPoint != null) {
            steering = new Vector3(pos.x - targetPoint.x, 0, pos.z - targetPoint.z).normalized;
            steering.Scale(new Vector3(weight, weight, weight));
        }
        if (targetObject != null) {
            steering = new Vector3(pos.x - targetObject.position.x, 0, pos.z - targetObject.position.z).normalized;
            steering.Scale(new Vector3(weight, weight, weight));
        }

        return steering;
    }
Exemplo n.º 20
0
    void Update()
    {
        //Randomly spawn enemies
        if (Random.value < spawnChance && enemyPrefab)
        {
            //Pick a position in a box around this object
            Vector3 pos = new Vector3(Random.Range(-0.5f, 0.5f), Random.Range(-0.5f, 0.5f), Random.Range(-0.5f, 0.5f));
            pos.Scale(spawnArea);

            //Spawn the enemy and put them in the right spot
            Enemy e = (Enemy)Instantiate(enemyPrefab);
            e.transform.position = transform.position + pos;

            //Parent them to us, so this object can receive messages on death
            e.transform.parent = transform;
        }
    }
Exemplo n.º 21
0
	// Update is called once per frame
	void Update () {

		if (Input.GetMouseButtonDown(0)) {
			Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
			RaycastHit hit;
			RaycastHit hit2;
			Vector3 movePosition = new Vector3(0,0,0);
			
			if(Physics.Raycast(ray, out hit, 100))
			{
				Debug.Log(ray.direction);
				//Ray newray = new Ray(hit.point - hit.normal * 1000f, hit.normal);
				Vector3 reverse = new Vector3(ray.direction.x * -1f, ray.direction.y * -1f, ray.direction.z * -1f);
				Debug.Log(reverse);
				reverse.Scale(new Vector3(5f, 5f, 5f));
				//Debug.Log("Final vector" + reverse);
				Vector3 newPosition = new Vector3(hit.point.x + reverse.x, hit.point.y + reverse.y, hit.point.z + reverse.z);
				//hit.collider.Raycast(newray, out hit2, 100);
				//Debug.Log ("reverse ray direction " + newray.direction);
			 	//ray.direction
				//Debug.Log("Current hitpoint: " + hit.point);
				//hit.point.Set(hit.point.x - (ray.direction.x * 2f), hit.point.y - (ray.direction.y * 2f), hit.point.z);
				//Debug.Log ("new hitpoint: " + hit.point);
				/*
				GameObject table = GameObject.Find("Table");
				if(table != null)
				{

					float distance = Vector3.Distance(table.transform.GetChild(0).position, this.gameObject.transform.position);
					for(int i = 1; i < table.transform.childCount; i++)
					{
						if(Vector3.Distance(table.transform.GetChild(i).position, this.gameObject.transform.position) < distance)
							movePosition = table.transform.GetChild(i).position;
					}
				}
				agent.SetDestination(movePosition);*/
				agent.SetDestination (hit.point);
				//Debug.Log("Old: " + hit.point);
				//Debug.Log("New: " + newPosition);
				//agent.SetDestination(newPosition);
			}
		
		}
	
	}
Exemplo n.º 22
0
    public override Vector3 GetPosition(MBParticle PT)
    {
        float theta=0;//=PT.Parent.Transform.rotation.eulerAngles.z*Mathf.Deg2Rad;
        if (!EvenlySpread)
            theta = Random.Range(-Arc, Arc);
        else if (DistributionPoints > 0) {
            theta =  -Arc + mDistributionStep * mDistribution++;
            if (mDistribution >= DistributionPoints)
                mDistribution = 0;
        }

        float d = Random.Range(Hollow, 1);

        Vector3 v = new Vector3(d * -Mathf.Sin(theta),
                                d * Mathf.Cos(theta),0);

        v.Scale(Scale);
        return v;
    }
Exemplo n.º 23
0
    public void UpdateWind()
    {
        if (getParentTarget && parentWind != null) {
            wind = parentWind.wind;
            localForces = parentWind.localForces;
            windStartHeight = parentWind.windStartHeight;
            if(getParentEmission)
                partiSystem.emissionRate = parentWind.partiSystem.emissionRate;
            return;
        }

        windTime += Time.deltaTime;

        if (windTime > windRandomness) {
            windTarget = Random.insideUnitSphere;
            windTarget.Scale (windStrength);
            windTime = 0f;
        }
        wind = Vector3.Lerp (wind, windTarget, windSmoothness);
    }
Exemplo n.º 24
0
    void SpawnEnemy()
    {
        //Pick a position in a box around this object
        Vector3 pos = new Vector3(Random.Range(-0.5f, 0.5f), Random.Range(-0.5f, 0.5f), Random.Range(-0.5f, 0.5f));
        pos.Scale(civilianSpawn.transform.position);

        //Spawn the enemy and put them in the right spot
        int derp = Random.Range(0, 3);
        if(derp == 0)
        {
            EnemyBehaviour e = (EnemyBehaviour)Instantiate(civilianPrefab);
            e.transform.position = transform.position + pos;

            //Parent them to us, so this object can receive messages on death
            e.transform.parent = transform;
        }
        if(derp == 1)
        {
            EnemyBehaviour e = (EnemyBehaviour)Instantiate(robberPrefab);
            e.transform.position = transform.position + pos;

            //Parent them to us, so this object can receive messages on death
            e.transform.parent = transform;
        }
        if(derp == 2)
        {
            EnemyBehaviour e = (EnemyBehaviour)Instantiate(copPrefab);
            e.transform.position = transform.position + pos;

            //Parent them to us, so this object can receive messages on death
            e.transform.parent = transform;
        }
        if(derp == 3)
        {
            EnemyBehaviour e = (EnemyBehaviour)Instantiate(hostileCopPrefab);
            e.transform.position = transform.position + pos;

            //Parent them to us, so this object can receive messages on death
            e.transform.parent = transform;
        }
    }
Exemplo n.º 25
0
    public IEnumerator ChooseDestination(float time, Vector3 faceDirection)
    {
        yield return new WaitForSeconds(time);

        isMoving = true;

        faceDirection.Scale(new Vector3(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f), 0));

        if (gameObject == alphaLeader) {
            faceDirection *= Random.Range(10, 30);
            destination = transform.position + faceDirection;
        }  else {
            faceDirection *= Random.Range(30, 100);
            destination = alphaLeader.transform.position + faceDirection;
        }

        destination[1] = 100;

        //		NavMeshHit hit;
        //
        //		if (NavMesh.SamplePosition(destination, out hit, 100, 1)) {
        //			destination = hit.position;
        //			agent.SetDestination(destination);
        //
        //			//CreateDestinationSphere(destination);
        //		}
        RaycastHit hit;
        Debug.DrawRay(destination, Vector3.down * 100);

        if (Physics.Raycast(destination, Vector3.down, out hit, 100)) {
            destination = hit.point;
            agent.SetDestination(destination);
        }

        //		if ((new Vector3(-12, transform.position.y, 60) - transform.position).magnitude) {
        //		} else if ((new Vector3(50, transform.position.y, 65) - transform.position).magnitude) {
        //		}

        //		CreateDestinationSphere(destination);
    }
Exemplo n.º 26
0
 IEnumerator SpawnTarget()
 {
     while (true)
     {
         yield return new WaitForSeconds(Random.Range(minSpawnTime, maxSpawnTime));
         if (Target != null)
         {
             GameObject curr = (GameObject)Instantiate(
                 Target,
                 new Vector3(Random.Range(-150, 150), -100, 0),
                 new Quaternion(Random.value, Random.value, Random.value, Random.value)
             );
             Vector3 force = new Vector3();
             force.x = curr.transform.position.x <= 0.0f ? 1 : -1;
             force.x *= Random.Range(minXForceFraction, 2);
             force.y = Random.Range(minYForceFraction, 3);
             force.z = 0;
             force.Scale(forceScale);
             curr.rigidbody.AddForce(force, ForceMode.Impulse);
             curr.rigidbody.angularVelocity = new Vector3(Random.Range(-150, 150), 0, 0);
         }
     }
 }
Exemplo n.º 27
0
 void LateUpdate ()
 {
     if (Input.GetKeyUp(KeyCode.F1))
     {
         experimental = !experimental;
     }
     if (!experimental)
     {
         transform.position = player.transform.position + offset;
     }
     else {
         
         transform.position = player.transform.position;
         Vector3 playerballvec = new Vector3(target.transform.position.x - player.transform.position.x, target.transform.position.y - player.transform.position.y, target.transform.position.z - player.transform.position.z);
         playerballvec.Normalize();
         playerballvec.Scale(new Vector3(3, 3, 3));
         transform.position = new Vector3(player.transform.position.x - 3*playerballvec.x,
                                         player.transform.position.y - playerballvec.y + 3,
                                         player.transform.position.z - 3*playerballvec.z);
         transform.LookAt(target.transform);
         
     }
 }
    private void Emit()
    {
        ParticleSystem.EmitParams emitParams = new ParticleSystem.EmitParams();

        Vector3 pos = Vector3.zero;

        switch (shape)
        {
            case KSPParticleEmitter.EmissionShape.Point:
                pos = Vector3.zero;
                break;

            case KSPParticleEmitter.EmissionShape.Line:
                pos = new Vector3(Random.Range(-shape1D, shape1D) * 0.5f, 0f, 0f);
                break;

            case KSPParticleEmitter.EmissionShape.Ellipsoid:
                pos = Random.insideUnitSphere;
                pos.Scale(shape3D);
                break;

            case KSPParticleEmitter.EmissionShape.Ellipse:
                pos = Random.insideUnitCircle;
                pos.x = pos.x * shape2D.x;
                pos.z = pos.y * shape2D.y;
                pos.y = 0f;
                break;

            case KSPParticleEmitter.EmissionShape.Sphere:
                pos = Random.insideUnitSphere * shape1D;
                break;

            case KSPParticleEmitter.EmissionShape.Cuboid:
                pos = new Vector3(
                    Random.Range(-shape3D.x, shape3D.x),
                    Random.Range(-shape3D.y, shape3D.y),
                    Random.Range(-shape3D.z, shape3D.z));
                break;

            case KSPParticleEmitter.EmissionShape.Plane:
                pos = new Vector3(Random.Range(-shape2D.x, shape2D.x), 0f, Random.Range(-shape2D.y, shape2D.y));
                break;

            case KSPParticleEmitter.EmissionShape.Ring:
                float posFloat = Random.Range(0f, 2f * Mathf.PI);
                pos = new Vector3(Mathf.Sin(posFloat) * shape2D.x, 0f, Mathf.Cos(posFloat) * shape2D.y);
                break;
        }

        Vector3 vel;
        if (pe.simulationSpace == ParticleSystemSimulationSpace.Local)
        {
            vel = localVelocity + new Vector3(
                      Random.Range(-rndVelocity.x, rndVelocity.x),
                      Random.Range(-rndVelocity.y, rndVelocity.y),
                      Random.Range(-rndVelocity.z, rndVelocity.z)) +
                  go.transform.InverseTransformDirection(worldVelocity);
        }
        else
        {
            pos = go.transform.TransformPoint(pos);
            vel = worldVelocity
                + go.transform.TransformDirection(
                    localVelocity
                    + new Vector3(
                        Random.Range(-rndVelocity.x, rndVelocity.x),
                        Random.Range(-rndVelocity.y, rndVelocity.y),
                        Random.Range(-rndVelocity.z, rndVelocity.z)
                        )
                    );
        }

        float rotation = rndRotation ? Random.value * 360f : 0f;
        float angularV = angularVelocity + Random.value * rndAngularVelocity;

        emitParams.position = pos;
        emitParams.velocity = vel;
        emitParams.rotation = rotation;
        emitParams.angularVelocity = angularV;
        emitParams.startLifetime = Random.Range(minEnergy, maxEnergy);
        emitParams.startColor = color;
        emitParams.startSize = Random.Range(minSize, maxSize);

        pe.Emit(emitParams, 1);
    }
Exemplo n.º 29
0
	//-------------------------------------------------------------------------
	/// <summary>
	/// Rotates and scales inputVertices and writes the result to the
	/// corresponding output array transformedVertices.
	/// </summary>
	/// <param name="inputVertices">Input vertices.</param>
	/// <param name="transformedVertices">Transformed vertices. Has to be of the same size as inputVertices.</param>
	void TransformReducedOutline(List<Vector2> inputVertices, Vector2[] transformedVertices) {

		// Order of vertex transformation is:
		// 1) rotated by initialRotationQuaternion around transformationCenter
		// 2) scaled by mVertexScaleAfterInitialRotation
		// 3) rotated by mVertexSecondRotationQuaternion around mVertexTransformationCenter
		// 4) scaled by mVertexScaleAfterSecondRotation
		// 3) translated by mVertexOffset

		float scaleX = GetOutputScaleX(false);
		float scaleY = GetOutputScaleY();
		
		Vector3 scaleAfterInitialRotation = new Vector3(scaleX, scaleY, 1);
		Vector3 scaleAfterSecondRotation = Vector3.one;
		
		float atlasFrameRotation = mAtlasFrameRotation;
		if (mRegionIndependentParameters.CustomTex != null) {
			scaleAfterInitialRotation.Scale(GetCustomImageScale());
			atlasFrameRotation = 0.0f;
		}

		// In order to rotate well, we need to compensate for the gameobject's
		// transform.scale that is applied automatically after all of our transforms.
		Vector3 automaticallyAppliedScale = this.transform.localScale;
		Vector3 rotationCompensationScaleBefore = new Vector3(automaticallyAppliedScale.x, automaticallyAppliedScale.y, 1.0f);
		Vector3 rotationCompensationScaleAfter = new Vector3(1.0f / automaticallyAppliedScale.x, 1.0f / automaticallyAppliedScale.y, 1.0f);
		scaleAfterInitialRotation.Scale(rotationCompensationScaleBefore);
		scaleAfterSecondRotation.Scale(rotationCompensationScaleAfter);

		Vector3 offset = new Vector3(mOutlineOffset.x + mRegionIndependentParameters.CustomOffset.x,
		                             mOutlineOffset.y + mRegionIndependentParameters.CustomOffset.y,
		                             mOutlineOffset.z + mRegionIndependentParameters.CustomOffset.z);
		Vector3 transformationCenter = new Vector3(0, 0, 0);
		Quaternion initialRotationQuaternion = Quaternion.Euler(0, 0, atlasFrameRotation);
		Quaternion secondRotationQuaternion = Quaternion.Euler(0, 0,  mRegionIndependentParameters.CustomRotation);

		for (int index = 0; index < inputVertices.Count; ++index) {
			Vector3 inputVertex = new Vector3(inputVertices[index].x, inputVertices[index].y, 0);
			Vector3 transformedVertex = inputVertex - transformationCenter;
			// rotate initially
			transformedVertex = initialRotationQuaternion * transformedVertex;
			// scale
			transformedVertex.Scale(scaleAfterInitialRotation);
			// rotate a second time
			transformedVertex = secondRotationQuaternion * transformedVertex;
			// scale 
			transformedVertex.Scale(scaleAfterSecondRotation);
			// translate
			transformedVertex += offset;
			transformedVertex += transformationCenter;
			
			// apply zLeftHandedMultiplier
			transformedVertices[index] = new Vector2(transformedVertex.x, transformedVertex.y);
		}
	}
Exemplo n.º 30
0
        private void Update()
        {
            if (!_lockedCursor && Input.GetMouseButtonDown(0))
            {
                _lockedCursor    = true;
                Cursor.lockState = CursorLockMode.Locked;
                Cursor.visible   = false;
            }
            else if (_lockedCursor && Input.GetKeyDown(KeyCode.Escape))
            {
                _lockedCursor    = false;
                Cursor.lockState = CursorLockMode.None;
                Cursor.visible   = true;
            }

            if (_lockedCursor)
            {
                var cursorDelta = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));

                Yaw   += cursorDelta.x * CursorSensitivity.x;
                Pitch -= cursorDelta.y * CursorSensitivity.y;
            }

            Camera.transform.rotation = Quaternion.AngleAxis(Yaw, Vector3.up)
                                        * Quaternion.AngleAxis(Pitch, Vector3.right);

            float   distance;
            Vector3 castFrom;

            if (_player.IsInVehicle)
            {
                CarCameraDistance = Mathf.Clamp(CarCameraDistance - Input.mouseScrollDelta.y, 2.0f, 32.0f);
                distance          = CarCameraDistance;
                castFrom          = _player.CurrentVehicle.transform.position;
            }
            else
            {
                PlayerCameraDistance = Mathf.Clamp(PlayerCameraDistance - Input.mouseScrollDelta.y, 2.0f, 32.0f);
                distance             = PlayerCameraDistance;
                castFrom             = transform.position + Vector3.up * .5f;
            }

            var castRay = new Ray(castFrom, -Camera.transform.forward);

            RaycastHit hitInfo;

            if (Physics.SphereCast(castRay, 0.25f, out hitInfo, distance,
                                   -1 ^ (1 << MapObject.BreakableLayer) ^ (1 << Vehicle.Layer)))
            {
                distance = hitInfo.distance;
            }

            Camera.transform.position = castRay.GetPoint(distance);

            if (Input.GetButtonDown("Use") && _player.IsInVehicle)
            {
                _player.ExitVehicle();

                return;
            }

            if (_player.IsInVehicle)
            {
                return;
            }
            if (!_lockedCursor)
            {
                return;
            }

            var inputMove = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));

            if (inputMove.sqrMagnitude > 0f)
            {
                inputMove.Normalize();

                if (Input.GetKey(KeyCode.LeftShift))
                {
                    PlayerModel.Running = true;
                }
                else
                {
                    PlayerModel.Walking = true;
                }
            }
            else
            {
                PlayerModel.Walking = false;
            }

            _player.Movement = Vector3.Scale(Camera.transform.TransformVector(inputMove),
                                             new Vector3(1f, 0f, 1f)).normalized;

            if (!Input.GetButtonDown("Use"))
            {
                return;
            }

            // find any vehicles that have a seat inside the checking radius and sort by closest seat
            var vehicles = FindObjectsOfType <Vehicle>()
                           .Where(x => Vector3.Distance(transform.position, x.FindClosestSeatTransform(transform.position).position) < EnterVehicleRadius)
                           .OrderBy(x => Vector3.Distance(transform.position, x.FindClosestSeatTransform(transform.position).position)).ToArray();

            foreach (var vehicle in vehicles)
            {
                var seat = vehicle.FindClosestSeat(transform.position);

                _player.EnterVehicle(vehicle, seat);

                break;
            }
        }
Exemplo n.º 31
0
        void SetupMesh(LetterAction letter_action, LetterAction prev_action, float action_progress, AnimationProgressionVariables progression_variables, AnimatePerOptions animate_per, float linear_progress, EffectManager effect_manager)
        {
            // construct current anchor offset vector
            m_anchor_offset = letter_action.AnchorOffsetStart;
            m_anchor_offset = new Vector3(m_anchor_offset.x * m_width,
                                          letter_action.m_letter_anchor_start == (int)TextfxTextAnchor.BaselineLeft || letter_action.m_letter_anchor_start == (int)TextfxTextAnchor.BaselineCenter || letter_action.m_letter_anchor_start == (int)TextfxTextAnchor.BaselineRight
                                                                                                ? 0             // zero because letters are based around the baseline already.
                                                                                                : (effect_manager.IsFontBaseLineSet
                                                                                                                ? (effect_manager.FontBaseLine + m_y_offset) - (m_anchor_offset.y * -m_height)
                                                                                                                : (m_anchor_offset.y * m_height)),      // Legacy effect support when baseline isn't already set.
                                          0);

            if (letter_action.m_letter_anchor_2_way)
            {
                m_anchor_offset = letter_action.AnchorOffsetEnd;
                m_anchor_offset = Vector3.Lerp(m_anchor_offset,
                                               new Vector3(
                                                   m_anchor_offset.x * m_width,
                                                   letter_action.m_letter_anchor_end == (int)TextfxTextAnchor.BaselineLeft || letter_action.m_letter_anchor_end == (int)TextfxTextAnchor.BaselineCenter || letter_action.m_letter_anchor_end == (int)TextfxTextAnchor.BaselineRight
                                                                                                                ? 0             // zero because letters are based around the baseline already.
                                                                                                                : (effect_manager.IsFontBaseLineSet
                                                                                                                                ? (effect_manager.FontBaseLine + m_y_offset) - (m_anchor_offset.y * -m_height)
                                                                                                                                : (m_anchor_offset.y * m_height)),      // Legacy effect support when baseline isn't already set.
                                                   0),
                                               action_progress);
            }


            // Calculate Scale Vector
            from_vec = letter_action.m_start_scale.GetValue(progression_variables, animate_per);
            to_vec   = letter_action.m_end_scale.GetValue(progression_variables, animate_per);

            if (letter_action.m_scale_axis_ease_data.m_override_default)
            {
                m_letter_scale = new Vector3(EffectManager.FloatLerp(from_vec.x, to_vec.x, EasingManager.GetEaseProgress(letter_action.m_scale_axis_ease_data.m_x_ease, linear_progress)),
                                             EffectManager.FloatLerp(from_vec.y, to_vec.y, EasingManager.GetEaseProgress(letter_action.m_scale_axis_ease_data.m_y_ease, linear_progress)),
                                             EffectManager.FloatLerp(from_vec.z, to_vec.z, EasingManager.GetEaseProgress(letter_action.m_scale_axis_ease_data.m_z_ease, linear_progress)));
            }
            else
            {
                m_letter_scale = EffectManager.Vector3Lerp(
                    from_vec,
                    to_vec,
                    action_progress);
            }

            // Calculate Rotation
            from_vec = letter_action.m_start_euler_rotation.GetValue(progression_variables, animate_per);
            to_vec   = letter_action.m_end_euler_rotation.GetValue(progression_variables, animate_per);

            if (letter_action.m_rotation_axis_ease_data.m_override_default)
            {
                m_letter_rotation = Quaternion.Euler
                                    (
                    EffectManager.FloatLerp(from_vec.x, to_vec.x, EasingManager.GetEaseProgress(letter_action.m_rotation_axis_ease_data.m_x_ease, linear_progress)),
                    EffectManager.FloatLerp(from_vec.y, to_vec.y, EasingManager.GetEaseProgress(letter_action.m_rotation_axis_ease_data.m_y_ease, linear_progress)),
                    EffectManager.FloatLerp(from_vec.z, to_vec.z, EasingManager.GetEaseProgress(letter_action.m_rotation_axis_ease_data.m_z_ease, linear_progress))
                                    );
            }
            else
            {
                m_letter_rotation = Quaternion.Euler(
                    EffectManager.Vector3Lerp(
                        from_vec,
                        to_vec,
                        action_progress)
                    );
            }


            // Calculate Position
            if (letter_action.m_start_pos.Progression == ActionPositionVector3Progression.CURVE_OPTION_INDEX || (letter_action.m_offset_from_last && prev_action != null && prev_action.m_end_pos.Progression == ActionPositionVector3Progression.CURVE_OPTION_INDEX))
            {
                from_vec = new Vector3(-m_anchor_offset.x, m_base_offset.y, 0);
            }
            else if (letter_action.m_start_pos.ForcePositionOverride)
            {
                from_vec = new Vector3(-m_anchor_offset.x, 0, 0);
            }
            else
            {
                from_vec = BaseOffset;
            }

            from_vec += letter_action.m_start_pos.GetValue(progression_variables, animate_per);

            if (letter_action.m_end_pos.Progression == ActionPositionVector3Progression.CURVE_OPTION_INDEX || (letter_action.m_end_pos.IsOffsetFromLast && letter_action.m_start_pos.Progression == ActionPositionVector3Progression.CURVE_OPTION_INDEX))
            {
                to_vec = new Vector3(-m_anchor_offset.x, m_base_offset.y, 0);
            }
            else if (letter_action.m_end_pos.ForcePositionOverride)
            {
                to_vec = new Vector3(-m_anchor_offset.x, 0, 0);
            }
            else
            {
                to_vec = BaseOffset;
            }

            to_vec += letter_action.m_end_pos.GetValue(progression_variables, animate_per);

            if (letter_action.m_position_axis_ease_data.m_override_default)
            {
                m_letter_position = new Vector3(EffectManager.FloatLerp(from_vec.x, to_vec.x, EasingManager.GetEaseProgress(letter_action.m_position_axis_ease_data.m_x_ease, linear_progress)),
                                                EffectManager.FloatLerp(from_vec.y, to_vec.y, EasingManager.GetEaseProgress(letter_action.m_position_axis_ease_data.m_y_ease, linear_progress)),
                                                EffectManager.FloatLerp(from_vec.z, to_vec.z, EasingManager.GetEaseProgress(letter_action.m_position_axis_ease_data.m_z_ease, linear_progress)));
            }
            else
            {
                m_letter_position = EffectManager.Vector3Lerp(
                    from_vec,
                    to_vec,
                    action_progress);
            }

            // Calculate letter center position
            m_letter_center  = new Vector3(m_width / 2, m_height / 2, 0);
            m_letter_center -= m_anchor_offset;
            m_letter_center  = Vector3.Scale(m_letter_center, m_letter_scale);
            m_letter_center  = m_letter_rotation * m_letter_center;
            m_letter_center += m_anchor_offset + m_letter_position;


            if (mesh_verts == null || mesh_verts.Length == 0)
            {
                mesh_verts = new Vector3[4];
            }
            for (int idx = 0; idx < 4; idx++)
            {
                mesh_verts[idx] = m_base_vertices[idx];

                // normalise vert position to the anchor point before scaling and rotating.
                mesh_verts[idx] -= m_anchor_offset;

                // Scale verts
                mesh_verts[idx] = Vector3.Scale(mesh_verts[idx], m_letter_scale);

                // Rotate vert
                mesh_verts[idx] = m_letter_rotation * mesh_verts[idx];

                mesh_verts[idx] += m_anchor_offset;

                // translate vert
                mesh_verts[idx] += m_letter_position;
            }
            m_mesh.vertices = mesh_verts;



            // Sort out letters colour
            if (letter_action.m_use_gradient_start)
            {
                start_colour = letter_action.m_start_vertex_colour.GetValue(progression_variables, animate_per);
            }
            else
            {
                start_colour = new VertexColour(letter_action.m_start_colour.GetValue(progression_variables, animate_per));
            }

            if (letter_action.m_use_gradient_end)
            {
                end_colour = letter_action.m_end_vertex_colour.GetValue(progression_variables, animate_per);
            }
            else
            {
                end_colour = new VertexColour(letter_action.m_end_colour.GetValue(progression_variables, animate_per));
            }

            if (!m_flipped)
            {
                m_mesh.colors = new Color[] {
                    Color.Lerp(start_colour.top_right, end_colour.top_right, action_progress),
                    Color.Lerp(start_colour.top_left, end_colour.top_left, action_progress),
                    Color.Lerp(start_colour.bottom_left, end_colour.bottom_left, action_progress),
                    Color.Lerp(start_colour.bottom_right, end_colour.bottom_right, action_progress)
                };
            }
            else
            {
                m_mesh.colors = new Color[] {
                    Color.Lerp(start_colour.top_left, end_colour.top_left, action_progress),
                    Color.Lerp(start_colour.bottom_left, end_colour.bottom_left, action_progress),
                    Color.Lerp(start_colour.bottom_right, end_colour.bottom_right, action_progress),
                    Color.Lerp(start_colour.top_right, end_colour.top_right, action_progress)
                };
            }
        }
Exemplo n.º 32
0
 public static Vector3 GetLocalFace( Vector3 halfExtents, Direction dir )
 {
   return Vector3.Scale( halfExtents, GetLocalFaceDirection( dir ) );
 }
    public void BuildMode()
    {
        if (buildMode)
        {
            if (currentBuildAsset == null)
            {
                if (inventory[inventoryCurrentIndex].amount > 0)
                {
                    currentBuildAsset = Instantiate(C.c.data.assetPrefab);
                    currentBuildAsset.Set(inventory[inventoryCurrentIndex].asset, "", true);
                    buildPlacementValid = false;
                    currentBuildAsset.model.GetComponent <MeshRenderer>().material = C.c.data.placingMats[1];
                    currentBuildCollider           = currentBuildAsset.model.AddComponent <BoxCollider>();
                    currentBuildCollider.isTrigger = true;
                }
            }
            if (currentBuildAsset)
            {
                RaycastHit hit;
                if (Physics.Raycast(cam.transform.position + cam.transform.forward, cam.transform.forward, out hit, 10f))
                {
                    var placementValid = buildPlacementValid;
                    if (Mathf.Abs(hit.normal.x) < .2f && Mathf.Abs(hit.normal.y) > .9f && Mathf.Abs(hit.normal.z) < .2f)
                    {
                        placementValid = true;
                    }
                    RaycastHit[] hits;
                    hits = Physics.BoxCastAll(currentBuildCollider.bounds.center, Vector3.Scale(currentBuildCollider.size, currentBuildAsset.model.transform.localScale) * .48f, Vector3.up, currentBuildAsset.transform.rotation, .01f);
                    foreach (RaycastHit h in hits)
                    {
                        if (h.transform != currentBuildAsset.model.transform && h.transform != transform)
                        {
                            placementValid = false;
                        }
                    }

                    if (placementValid)
                    {
                        if (!buildPlacementValid)
                        {
                            currentBuildAsset.model.GetComponent <MeshRenderer>().material = C.c.data.placingMats[0];
                        }
                        buildPlacementValid = true;
                    }
                    else
                    {
                        if (buildPlacementValid)
                        {
                            currentBuildAsset.model.GetComponent <MeshRenderer>().material = C.c.data.placingMats[1];
                        }
                        buildPlacementValid = false;
                    }

                    var ydiff = currentBuildAsset.transform.position.y - (currentBuildCollider.bounds.center.y - currentBuildCollider.bounds.extents.y);
                    if (currentBuildAsset.physicsAsset)
                    {
                        currentBuildAsset.transform.position = hit.point + Vector3.up * +(ydiff + .05f);
                    }
                    else
                    {
                        currentBuildAsset.transform.position = hit.point + Vector3.up * ydiff;
                    }

                    if (InputManager.RotatePlacement(playerId) != 0)
                    {
                        currentBuildAsset.transform.Rotate(0, .7f * InputManager.RotatePlacement(playerId), 0);
                        if (Input.GetKey(KeyCode.LeftShift))
                        {
                            currentBuildAsset.transform.Rotate(0, .7f * InputManager.RotatePlacement(playerId), 0);
                        }
                    }
                    if ((InputManager.PlaceAsset(playerId) || InputManager.JumpInput(playerId)) && buildPlacementValid)
                    {
                        currentBuildAsset.placing = false;
                        currentBuildAsset.Set(currentBuildAsset.data);
                        if (InputManager.AutoSellWhilePlacing(playerId))
                        {
                            currentBuildAsset.ToggleSelling();
                        }
                        currentBuildAsset = null;
                        inventory[inventoryCurrentIndex].amount--;
                        pui.invRender.UpdateInventoryRender();
                        C.c.currentShop.UpdateShop();
                    }
                }
            }
        }

        //Start / stop Build Mode
        if (InputManager.BuildModeInput(playerId) || (buildMode && InputManager.Cancel(playerId)))
        {
            buildMode = !buildMode;
            pui.modeStatusText.transform.parent.gameObject.SetActive(buildMode);
            if (!buildMode)
            {
                if (currentBuildAsset)
                {
                    Destroy(currentBuildAsset.gameObject);
                }
            }
        }
    }
Exemplo n.º 34
0
 public void Drag()
 {
     if (!this.mPressed || UICamera.currentScheme == UICamera.ControlScheme.Controller)
     {
         return;
     }
     if (base.enabled && NGUITools.GetActive(base.gameObject) && this.mShouldMove)
     {
         if (this.mDragID == -10)
         {
             this.mDragID = UICamera.currentTouchID;
         }
         UICamera.currentTouch.clickNotification = UICamera.ClickNotification.BasedOnDelta;
         if (this.smoothDragStart && !this.mDragStarted)
         {
             this.mDragStarted     = true;
             this.mDragStartOffset = UICamera.currentTouch.totalDelta;
             if (this.onDragStarted != null)
             {
                 this.onDragStarted();
             }
         }
         Ray   ray      = (!this.smoothDragStart) ? UICamera.currentCamera.ScreenPointToRay(UICamera.currentTouch.pos) : UICamera.currentCamera.ScreenPointToRay(UICamera.currentTouch.pos - this.mDragStartOffset);
         float distance = 0f;
         if (this.mPlane.Raycast(ray, out distance))
         {
             Vector3 point  = ray.GetPoint(distance);
             Vector3 vector = point - this.mLastPos;
             this.mLastPos = point;
             if (vector.x != 0f || vector.y != 0f || vector.z != 0f)
             {
                 vector = this.mTrans.InverseTransformDirection(vector);
                 if (this.movement == UIScrollView.Movement.Horizontal)
                 {
                     vector.y = 0f;
                     vector.z = 0f;
                 }
                 else if (this.movement == UIScrollView.Movement.Vertical)
                 {
                     vector.x = 0f;
                     vector.z = 0f;
                 }
                 else if (this.movement == UIScrollView.Movement.Unrestricted)
                 {
                     vector.z = 0f;
                 }
                 else
                 {
                     vector.Scale(this.customMovement);
                 }
                 vector = this.mTrans.TransformDirection(vector);
             }
             if (this.dragEffect == UIScrollView.DragEffect.None)
             {
                 this.mMomentum = Vector3.zero;
             }
             else
             {
                 this.mMomentum = Vector3.Lerp(this.mMomentum, this.mMomentum + vector * (0.01f * this.momentumAmount), 0.67f);
             }
             if (!this.iOSDragEmulation || this.dragEffect != UIScrollView.DragEffect.MomentumAndSpring)
             {
                 this.MoveAbsolute(vector);
             }
             else
             {
                 Vector3 vector2 = this.mPanel.CalculateConstrainOffset(this.bounds.min, this.bounds.max);
                 if (this.movement == UIScrollView.Movement.Horizontal)
                 {
                     vector2.y = 0f;
                 }
                 else if (this.movement == UIScrollView.Movement.Vertical)
                 {
                     vector2.x = 0f;
                 }
                 else if (this.movement == UIScrollView.Movement.Custom)
                 {
                     vector2.x *= this.customMovement.x;
                     vector2.y *= this.customMovement.y;
                 }
                 if (vector2.magnitude > 1f)
                 {
                     this.MoveAbsolute(vector * 0.5f);
                     this.mMomentum *= 0.5f;
                 }
                 else
                 {
                     this.MoveAbsolute(vector);
                 }
             }
             if (this.constrainOnDrag && this.restrictWithinPanel && this.mPanel.clipping != UIDrawCall.Clipping.None && this.dragEffect != UIScrollView.DragEffect.MomentumAndSpring)
             {
                 this.RestrictWithinBounds(true, this.canMoveHorizontally, this.canMoveVertically);
             }
         }
     }
 }
Exemplo n.º 35
0
    public override void PlaySkill(int skillNum, int option)
    {
        Transform   trns = PlayerController.Instance.transform;
        Rigidbody2D rb2D = PlayerController.Instance.GetComponent <Rigidbody2D>();

        switch (skillNum)
        {
        case 0:
            EffectPool.Instance.StartEffect(GameManager.Instance.effectAnim["BWSpear00"], trns.position + Vector3.Scale(new Vector3(2.5f, 1, 0), trns.localScale), trns.localScale);
            if (PlayerController.Instance.controller.m_Grounded)
            {
                rb2D.velocity = new Vector2(0, 0);
            }
            else
            {
                rb2D.velocity     = new Vector2(0, 0);
                rb2D.gravityScale = 0;
            }
            break;

        case 1:
            EffectPool.Instance.StartEffect(GameManager.Instance.effectAnim["BWSpear01"], trns.position + Vector3.Scale(new Vector3(2.5f, 1, 0), trns.localScale), trns.localScale);
            if (PlayerController.Instance.controller.m_Grounded)
            {
                rb2D.velocity = new Vector2(0, 0);
            }
            else
            {
                rb2D.velocity     = new Vector2(0, 0);
                rb2D.gravityScale = 0;
            }
            break;
        }
    }
Exemplo n.º 36
0
 public Vector3 GetSpawnOffset(Vector3 local_bounds_extents) =>
 SpawnOffset.IsZero() ?
 SpawnOffset :
 Vector3.Scale(local_bounds_extents, SpawnOffset);
Exemplo n.º 37
0
    void LegacySetParticle()
    {
        ParticleEmitter  pe = m_pe;
        ParticleAnimator pa = m_pa;
        ParticleRenderer pr = m_pr;

        if (pe == null || pr == null)
        {
            return;
        }

        if (m_bLegacyRuntimeScale)
        {
            Vector3 vecVelScale = Vector3.one * m_fStartSpeedRate;
            float   fVelScale   = m_fStartSpeedRate;

            pe.minSize     *= m_fStartSizeRate;
            pe.maxSize     *= m_fStartSizeRate;
            pe.minEnergy   *= m_fStartLifeTimeRate;
            pe.maxEnergy   *= m_fStartLifeTimeRate;
            pe.minEmission *= m_fStartEmissionRate;
            pe.maxEmission *= m_fStartEmissionRate;

            pe.worldVelocity         = Vector3.Scale(pe.worldVelocity, vecVelScale);
            pe.localVelocity         = Vector3.Scale(pe.localVelocity, vecVelScale);
            pe.rndVelocity           = Vector3.Scale(pe.rndVelocity, vecVelScale);
            pe.angularVelocity      *= fVelScale;
            pe.rndAngularVelocity   *= fVelScale;
            pe.emitterVelocityScale *= fVelScale;

//          NgAssembly.LogFieldsPropertis(pe);

            if (pa != null)
            {
                pa.rndForce = Vector3.Scale(pa.rndForce, vecVelScale);
                pa.force    = Vector3.Scale(pa.force, vecVelScale);
//				pa.damping					*= fScale;
            }

//          pr.velocityScale			*= fVelScale;
            pr.lengthScale *= m_fRenderLengthRate;
        }
        else
        {
            Vector3 vecVelScale = (m_bScaleWithTransform ? pe.transform.lossyScale : Vector3.one) * m_fStartSpeedRate;
            float   fVelScale   = (m_bScaleWithTransform ? NcTransformTool.GetTransformScaleMeanValue(pe.transform) : 1) * m_fStartSpeedRate;
            float   fScale      = (m_bScaleWithTransform ? NcTransformTool.GetTransformScaleMeanValue(pe.transform) : 1) * m_fStartSizeRate;

            pe.minSize     *= fScale;
            pe.maxSize     *= fScale;
            pe.minEnergy   *= m_fStartLifeTimeRate;
            pe.maxEnergy   *= m_fStartLifeTimeRate;
            pe.minEmission *= m_fStartEmissionRate;
            pe.maxEmission *= m_fStartEmissionRate;

            pe.worldVelocity         = Vector3.Scale(pe.worldVelocity, vecVelScale);
            pe.localVelocity         = Vector3.Scale(pe.localVelocity, vecVelScale);
            pe.rndVelocity           = Vector3.Scale(pe.rndVelocity, vecVelScale);
            pe.angularVelocity      *= fVelScale;
            pe.rndAngularVelocity   *= fVelScale;
            pe.emitterVelocityScale *= fVelScale;

//          NgAssembly.LogFieldsPropertis(pe);

            if (pa != null)
            {
                pa.rndForce = Vector3.Scale(pa.rndForce, vecVelScale);
                pa.force    = Vector3.Scale(pa.force, vecVelScale);
//				pa.damping					*= fScale;
            }

//          pr.velocityScale			*= fVelScale;
            pr.lengthScale *= m_fRenderLengthRate;
        }
    }
Exemplo n.º 38
0
    void Update()
    {
        float delta = Time.deltaTime;
        bool  shift = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);

        float       a = hitbox.color.a;
        const float hitboxFadeSpeed = 4F;

        if (shift && allowInput)
        {
            a = Mathf.Min(1, a + hitboxFadeSpeed * delta);
        }
        else
        {
            a = Mathf.Max(0, a - hitboxFadeSpeed * delta);
        }

        if (!allowInput)
        {
            return;
        }

        if (iframes > 0)
        {
            iframes -= delta;

            if (iframes < 0)
            {
                gameObject.layer = 10; // Player
                sprite.color     = new Color32(255, 255, 255, 255);
            }
        }

        float motionX = 0, motionY = 0;
        float speed = (shift ? moveSpeedShift : moveSpeed) * delta;

        if (Input.GetKey(KeyCode.UpArrow))
        {
            motionY += 1;
        }
        if (Input.GetKey(KeyCode.DownArrow))
        {
            motionY -= 1;
        }

        if (Input.GetKey(KeyCode.RightArrow))
        {
            motionX += 1;
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            motionX -= 1;
        }

        Vector3 motion = new Vector3(motionX, motionY, 0);

        motion.Normalize();
        motion.Scale(new Vector3(speed, speed, 0));

        transform.position += motion;
        ClampPosition();

        hitbox.color = new Color(1F, 1F, 1F, a);
    }
Exemplo n.º 39
0
    protected virtual void Update()
    {
        if (useProfileHeight)
        {
            if (InitialPose == null)
            {
                InitialPose = new OVRPose()
                {
                    position    = CameraController.transform.localPosition,
                    orientation = CameraController.transform.localRotation
                };
            }

            var p = CameraController.transform.localPosition;
            p.y = OVRManager.profile.eyeHeight - 0.5f * Controller.height;
            p.z = OVRManager.profile.eyeDepth;
            CameraController.transform.localPosition = p;
        }
        else if (InitialPose != null)
        {
            CameraController.transform.localPosition = InitialPose.Value.position;
            CameraController.transform.localRotation = InitialPose.Value.orientation;
            InitialPose = null;
        }

        UpdateMovement();

        Vector3 moveDirection = Vector3.zero;

        float motorDamp = (1.0f + (Damping * SimulationRate * Time.deltaTime));

        MoveThrottle.x /= motorDamp;
        MoveThrottle.y  = (MoveThrottle.y > 0.0f) ? (MoveThrottle.y / motorDamp) : MoveThrottle.y;
        MoveThrottle.z /= motorDamp;

        moveDirection += MoveThrottle * SimulationRate * Time.deltaTime;

        // Gravity
        if (Controller.isGrounded && FallSpeed <= 0)
        {
            FallSpeed = ((Physics.gravity.y * (GravityModifier * 0.002f)));
        }
        else
        {
            FallSpeed += ((Physics.gravity.y * (GravityModifier * 0.002f)) * SimulationRate * Time.deltaTime);
        }

        moveDirection.y += FallSpeed * SimulationRate * Time.deltaTime;

        // Offset correction for uneven ground
        float bumpUpOffset = 0.0f;

        if (Controller.isGrounded && MoveThrottle.y <= 0.001f)
        {
            bumpUpOffset   = Mathf.Max(Controller.stepOffset, new Vector3(moveDirection.x, 0, moveDirection.z).magnitude);
            moveDirection -= bumpUpOffset * Vector3.up;
        }

        Vector3 predictedXZ = Vector3.Scale((Controller.transform.localPosition + moveDirection), new Vector3(1, 0, 1));

        // Move contoller
        Controller.Move(moveDirection);

        Vector3 actualXZ = Vector3.Scale(Controller.transform.localPosition, new Vector3(1, 0, 1));

        if (predictedXZ != actualXZ)
        {
            MoveThrottle += (actualXZ - predictedXZ) / (SimulationRate * Time.deltaTime);
        }
    }
Exemplo n.º 40
0
        public override void ToMesh()
        {
            int axisDivisions = m_subdivisions;

            Mesh m = new Mesh();

            m.name = "Cone";
            float radius = .5f;

            axisDivisions++;

            Vector3[] circle = new Vector3[axisDivisions];

            for (int i = 0; i < axisDivisions - 1; i++)
            {
                float theta = ((360f / (axisDivisions - 1)) * i) * Mathf.Deg2Rad;

                float x = Mathf.Cos(theta) * radius;
                float z = Mathf.Sin(theta) * radius;

                circle[i] = new Vector3(x, -.5f, z);
            }

            circle[axisDivisions - 1] = circle[0];

            int vertexCount = (axisDivisions * 2) + 2;

            // verts
            Vector3[] v = new Vector3[vertexCount];
            // Vector3[] nrm = new Vector3[vertexCount];

            for (int i = 0; i < axisDivisions; i++)
            {
                v[i] = circle[i];                               // bottom for sides
                v[i + axisDivisions] = circle[i];               // bottom for -v.up
            }

            // circle point
            v[vertexCount - 2] = Vector3.up * -.5f;

            // cone point
            v[vertexCount - 1] = Vector3.up * .5f;

            int[] tris = new int[(axisDivisions * 3) * 2];

            int n    = 0;
            int step = axisDivisions * 3;

            for (int i = 0; i < axisDivisions - 1; i++)
            {
                // cone sides
                tris[n + 0] = i;
                tris[n + 1] = vertexCount - 1;
                tris[n + 2] = i + 1;

                // // bottom circle
                tris[n + step + 0] = i + axisDivisions + 1;
                tris[n + step + 1] = vertexCount - 2;
                tris[n + step + 2] = i + axisDivisions;

                n += 3;
            }

            //reassign scale
            LocalScale.x = Mathf.Abs(LocalScale.x);
            LocalScale.y = Mathf.Abs(LocalScale.y);
            LocalScale.z = Mathf.Abs(LocalScale.z);

            for (int i = 0; i < v.Length; i++)
            {
                v[i] = Vector3.Scale(v[i], LocalScale);
            }


            m.vertices  = v;
            m.triangles = tris;
            m.uv        = new Vector2[m.vertices.Length];

            GetComponent <MeshFilter>().sharedMesh = m;

            if (GetComponent <MeshRenderer>().sharedMaterial == null)
            {
                GetComponent <MeshRenderer>().sharedMaterial = DefaultDiffuse;
            }

            m.RecalculateNormals();
        }
Exemplo n.º 41
0
        public Vector3 AbsoluteFromRelative(Vector3 p)
        {
            Vector3 size = bottomRight.transform.position - topLeft.transform.position;

            return(bottomRight.transform.position + Vector3.Scale(size, p));
        }
 void Start()
 {
     dir = new Vector3(Random.Range(0.0f, 360.0f), Random.Range(0.0f, 360.0f), Random.Range(0.0f, 360.0f)).normalized;
     dir.Scale(axis);
     dir += baseDir;
 }
Exemplo n.º 43
0
 private void OnDrawGizmos()
 {
     Gizmos.DrawWireCube(this.transform.position, Vector3.Scale(new Vector3(0.64f, 0.64f, 0.0f), new Vector3(m_Width, 1.0f, 1.0f)));
 }
Exemplo n.º 44
0
        /// <summary>
        /// Initialize variables, callbacks and check null references.
        /// </summary>
        void Start()
        {
            _controllerConnectionHandler = GetComponent <ControllerConnectionHandler>();

            if (!_controllerConnectionHandler.enabled)
            {
                Debug.LogError("Error ControllerVisualizer starting MLInput, disabling script.");
                enabled = false;
                return;
            }
            if (!_controllerModel)
            {
                Debug.LogError("Error ControllerVisualizer._controllerModel not set, disabling script.");
                enabled = false;
                return;
            }
            if (!_trigger)
            {
                Debug.LogError("Error ControllerVisualizer._trigger not set, disabling script.");
                enabled = false;
                return;
            }
            if (!_touchpad)
            {
                Debug.LogError("Error ControllerVisualizer._touchpad not set, disabling script.");
                enabled = false;
                return;
            }
            if (!_homeButton)
            {
                Debug.LogError("Error ControllerVisualizer._homeButton not set, disabling script.");
                enabled = false;
                return;
            }
            if (!_bumperButton)
            {
                Debug.LogError("Error ControllerVisualizer._bumperButton not set, disabling script.");
                enabled = false;
                return;
            }
            if (!_touchIndicatorTransform)
            {
                Debug.LogError("Error ControllerVisualizer._touchIndicatorTransform not set, disabling script.");
                enabled = false;
                return;
            }

            SetVisibility(_controllerConnectionHandler.IsControllerValid());

            MLInput.OnControllerButtonUp   += HandleOnButtonUp;
            MLInput.OnControllerButtonDown += HandleOnButtonDown;

            _triggerMaterial      = FindMaterial(_trigger);
            _touchpadMaterial     = FindMaterial(_touchpad);
            _homeButtonMaterial   = FindMaterial(_homeButton);
            _bumperButtonMaterial = FindMaterial(_bumperButton);

            // Calculate the radius of the touchpad's mesh
            Mesh mesh = _touchpad.GetComponent <MeshFilter>().mesh;

            _touchpadRadius = Vector3.Scale(mesh.bounds.extents, _touchpad.transform.lossyScale).x;

            //MARK'S CODE:
            StepTracker.instance.controller = controllerCollider;
        }
Exemplo n.º 45
0
    protected Vector3 GetPalmCenter()
    {
        Vector3 offset = PALM_CENTER_OFFSET * Vector3.Scale(GetPalmDirection(), transform.localScale);

        return(GetPalmPosition() - offset);
    }
Exemplo n.º 46
0
    protected virtual void Update()
    {
        if (useProfileData)
        {
            if (InitialPose == null)
            {
                // Save the initial pose so it can be recovered if useProfileData
                // is turned off later.
                InitialPose = new OVRPose()
                {
                    position    = CameraRig.transform.localPosition,
                    orientation = CameraRig.transform.localRotation
                };
            }

            var p = CameraRig.transform.localPosition;
            if (OVRManager.instance.trackingOriginType == OVRManager.TrackingOrigin.EyeLevel)
            {
                p.y = OVRManager.profile.eyeHeight - (0.5f * Controller.height) + Controller.center.y;
            }
            else if (OVRManager.instance.trackingOriginType == OVRManager.TrackingOrigin.FloorLevel)
            {
                p.y = -(0.5f * Controller.height) + Controller.center.y;
            }
            CameraRig.transform.localPosition = p;
        }
        else if (InitialPose != null)
        {
            // Return to the initial pose if useProfileData was turned off at runtime
            CameraRig.transform.localPosition = InitialPose.Value.position;
            CameraRig.transform.localRotation = InitialPose.Value.orientation;
            InitialPose = null;
        }

        UpdateMovement();

        Vector3 moveDirection = Vector3.zero;

        float motorDamp = (1.0f + (Damping * SimulationRate * Time.deltaTime));

        MoveThrottle.x /= motorDamp;
        MoveThrottle.y  = (MoveThrottle.y > 0.0f) ? (MoveThrottle.y / motorDamp) : MoveThrottle.y;
        MoveThrottle.z /= motorDamp;

        moveDirection += MoveThrottle * SimulationRate * Time.deltaTime;

        // Gravity
        if (Controller.isGrounded && FallSpeed <= 0)
        {
            FallSpeed = ((Physics.gravity.y * (GravityModifier * 0.002f)));
        }
        else
        {
            FallSpeed += ((Physics.gravity.y * (GravityModifier * 0.002f)) * SimulationRate * Time.deltaTime);
        }

        moveDirection.y += FallSpeed * SimulationRate * Time.deltaTime;

        // Offset correction for uneven ground
        float bumpUpOffset = 0.0f;

        if (Controller.isGrounded && MoveThrottle.y <= transform.lossyScale.y * 0.001f)
        {
            bumpUpOffset   = Mathf.Max(Controller.stepOffset, new Vector3(moveDirection.x, 0, moveDirection.z).magnitude);
            moveDirection -= bumpUpOffset * Vector3.up;
        }

        Vector3 predictedXZ = Vector3.Scale((Controller.transform.localPosition + moveDirection), new Vector3(1, 0, 1));

        // Move contoller
        Controller.Move(moveDirection);

        Vector3 actualXZ = Vector3.Scale(Controller.transform.localPosition, new Vector3(1, 0, 1));

        if (predictedXZ != actualXZ)
        {
            MoveThrottle += (actualXZ - predictedXZ) / (SimulationRate * Time.deltaTime);
        }
    }
Exemplo n.º 47
0
    // Use this for initialization
    void Start()
    {
        if (Application.isPlaying && uiAnimation != null)
        {
            return;
        }

        rect = GetComponent <RectTransform>();

        List <UIAnimation> animations = new List <UIAnimation>();

        if (moveAnimation)
        {
            UpdateBehaviour     mod = EasyUIAnimatorUtils.GetModifier(moveModifier);
            Effect.EffectUpdate eff = EasyUIAnimatorUtils.GetEffect(moveEffect, max[0], bounce[0]);
            effectRotation = (randomDirection) ? Vector3.forward * Random.Range(0, 360) : effectRotation;
            if (useScreenValues)
            {
                uiAnimation = UIAnimator.Move(rect, Vector3.Scale(start[0], (Vector3)UIAnimator.InvertedScreenDimension), Vector3.Scale(final[0], (Vector3)UIAnimator.InvertedScreenDimension), duration).SetDelay(delay).SetModifier(mod).SetEffect(eff, Quaternion.Euler(effectRotation));
            }
            else
            {
                animations.Add(UIAnimator.Move(rect, start[0], final[0], duration).SetModifier(mod).SetEffect(eff, Quaternion.Euler(effectRotation)));
            }
        }
        if (scaleAnimation)
        {
            UpdateBehaviour     mod = EasyUIAnimatorUtils.GetModifier(scaleModifier);
            Effect.EffectUpdate eff = EasyUIAnimatorUtils.GetEffect(scaleEffect, max[1], bounce[1]);
            animations.Add(UIAnimator.Scale(rect, start[1], final[1], duration).SetModifier(mod).SetEffect(eff));
        }
        if (rotationAnimation)
        {
            UpdateBehaviour     mod = EasyUIAnimatorUtils.GetModifier(rotationModifier);
            Effect.EffectUpdate eff = EasyUIAnimatorUtils.GetEffect(rotationEffect, max[2], bounce[2]);
            if (start[2].x != 0 || start[2].y != 0 || final[2].x != 0 || final[2].y != 0)
            {
                animations.Add(UIAnimator.Rotate(rect, Quaternion.Euler(start[2]), Quaternion.Euler(final[2]), duration).SetModifier(mod).SetEffect(eff));
            }
            else
            {
                animations.Add(UIAnimator.Rotate(rect, start[2].z, final[2].z, duration).SetModifier(mod).SetEffect(eff));
            }
        }
        if (graphicAnimation)
        {
            UpdateBehaviour mod = EasyUIAnimatorUtils.GetModifier(graphicModifier);
            image = GetComponent <Graphic>();
            if (!image)
            {
                Debug.LogError("Please attach an Image/Text component to the gameObject");
            }
            else
            {
                animations.Add(UIAnimator.ChangeColor(image, startColor, finalColor, duration).SetDelay(delay).SetModifier(mod));
            }
        }

        if (animations.Count == 0)
        {
            Debug.Log("No animation");
            return;
        }
        else
        {
            uiAnimation = new UIGroupAnimation(animations.ToArray()).SetDelay(delay);
        }

        switch (loop)
        {
        case Loop.LOOP:
            uiAnimation.SetLoop();
            break;

        case Loop.PING_PONG:
            uiAnimation.SetLoop(true);
            break;
        }

        if (disableAfter)
        {
            uiAnimation.SetCallback(() => { gameObject.SetActive(false); });
        }
        if (Application.isPlaying)
        {
            if (playOnStart)
            {
                Play();
            }
        }
    }
        private void UpdateHandles(Foliage2D_Path path2D, GUIStyle iconStyle)
        {
            Quaternion inv = Quaternion.Inverse(path2D.transform.rotation);

            Handles.color = new Color(1, 1, 1, 0);
            Vector3 global, tGlobal = Vector3.zero;

            handleSelected = false;

            for (int i = 0; i < path2D.handlesPosition.Count; i++)
            {
                // global position of a path point
                Vector3 pos        = path2D.transform.position + Vector3.Scale(new Vector3(path2D.handlesPosition[i].x, path2D.handlesPosition[i].y, 0), path2D.transform.localScale);
                Vector3 tPos       = path2D.transform.position + Vector3.Scale(new Vector3(path2D.handleControlsPos[i].x, path2D.handleControlsPos[i].y, 0), path2D.transform.localScale);
                bool    isSelected = selectedPoints.Contains(i);

                if (!handleSelected)
                {
                    handleSelected = selectedPoints.Contains(i);
                }

                Texture2D tex = null;
                tex = isSelected ? texDotSelected : texDot;

                if (IsVisible(pos))
                {
                    SetScale(pos, tex, ref iconStyle);
                    Handles.Label(pos, new GUIContent(tex), iconStyle);
                }

                if (!path2D.uniformValues && path2D.foliagePathType == Foliage2D_PathType.Smooth && IsVisible(tPos) && selectedPoints.Contains(i))
                {
                    SetScale(tPos, texBlueDot, ref iconStyle);
                    Handles.Label(tPos, new GUIContent(texBlueDot), iconStyle);
                }

                global = Handles.FreeMoveHandle(pos, Quaternion.identity, HandleScale(pos), Vector3.zero, Handles.CircleHandleCap);

                if (!path2D.uniformValues && path2D.foliagePathType == Foliage2D_PathType.Smooth)
                {
                    tGlobal = Handles.FreeMoveHandle(tPos, Quaternion.identity, HandleScale(tPos), Vector3.zero, Handles.CircleHandleCap);
                }

                if (global != pos)
                {
                    selectedPoints.Clear();
                    selectedPoints.Add(i);
                    isSelected = true;

                    Vector3 local = inv * (global - path2D.transform.position);

                    Vector2 relative = new Vector2(
                        local.x / path2D.transform.localScale.x,
                        local.y / path2D.transform.localScale.y) - path2D.handlesPosition[i];

                    path2D.handlesPosition[selectedPoints[0]]   += relative;
                    path2D.handleControlsPos[selectedPoints[0]] += relative;

                    index = i;
                }

                if (tGlobal != tPos && !path2D.uniformValues && path2D.foliagePathType == Foliage2D_PathType.Smooth)
                {
                    Vector3 local = inv * (tGlobal - path2D.transform.position);

                    Vector2 relative = new Vector2(
                        local.x / path2D.transform.localScale.x,
                        local.y / path2D.transform.localScale.y) - path2D.handleControlsPos[i];

                    path2D.handleControlsPos[selectedPoints[0]] += relative;
                    path2D.nodeTension[i] = -Vector2.Distance(path2D.handleControlsPos[i], path2D.handlesPosition[i]) + 2f;

                    Vector2 line       = path2D.handleControlsPos[i] - path2D.handlesPosition[i];
                    float   angleInDeg = Mathf.Atan2(line.y, line.x) * Mathf.Rad2Deg;

                    if (angleInDeg > 0)
                    {
                        path2D.nodeBias[i] = -4 * angleInDeg / 180f;
                    }
                    else
                    {
                        path2D.nodeBias[i] = -4 * angleInDeg / 180f;
                    }
                }

                // make sure we can add new point at the midpoints!
                if (i + 1 < path2D.handlesPosition.Count)
                {
                    int     index       = i + 1;
                    Vector3 pos2        = path2D.transform.position + path2D.transform.rotation * Vector3.Scale(new Vector3(path2D.handlesPosition[index].x, path2D.handlesPosition[index].y, 0), path2D.transform.localScale);
                    Vector3 mid         = (pos + pos2) / 2;
                    float   handleScale = HandleScale(mid);

                    if (Handles.Button(mid, SceneView.lastActiveSceneView.camera.transform.rotation, handleScale, handleScale, Handles.CircleHandleCap))
                    {
                        Vector2 pt = inv * new Vector2((mid.x - path2D.transform.position.x) / path2D.transform.localScale.x, (mid.y - path2D.transform.position.y) / path2D.transform.localScale.y);

                        path2D.handlesPosition.Insert(index, pt);
                        path2D.handleControlsPos.Insert(index, new Vector2(pt.x + 2f, pt.y));
                        path2D.nodeTension.Insert(index, 0f);
                        path2D.nodeBias.Insert(index, 0f);
                    }
                    if (IsVisible(mid))
                    {
                        SetScale(mid, texDotPlus, ref iconStyle);
                        Handles.Label(mid, new GUIContent(texDotPlus), iconStyle);
                    }
                }

                // check if we want to remove points
                if (Event.current.alt && path2D.handlesPosition.Count > 2)
                {
                    float handleScale = HandleScale(pos);
                    if (IsVisible(pos))
                    {
                        SetScale(pos, texMinus, ref iconStyle);
                        Handles.Label(pos, new GUIContent(texMinus), iconStyle);
                    }

                    if (Handles.Button(pos, SceneView.lastActiveSceneView.camera.transform.rotation, handleScale, handleScale, Handles.CircleHandleCap))
                    {
                        if (!isSelected)
                        {
                            selectedPoints.Clear();
                            selectedPoints.Add(i);
                        }
                        for (int s = 0; s < selectedPoints.Count; s++)
                        {
                            path2D.handlesPosition.RemoveAt(selectedPoints[s]);
                            path2D.handleControlsPos.RemoveAt(selectedPoints[s]);
                            path2D.nodeTension.RemoveAt(selectedPoints[s]);
                            path2D.nodeBias.RemoveAt(selectedPoints[s]);

                            if (selectedPoints[s] <= i)
                            {
                                i--;
                            }

                            for (int u = 0; u < selectedPoints.Count; u++)
                            {
                                if (selectedPoints[u] > selectedPoints[s])
                                {
                                    selectedPoints[u] -= 1;
                                }
                            }
                        }
                        selectedPoints.Clear();
                        GUI.changed = true;
                    }
                }
            }
        }
Exemplo n.º 49
0
 public override void UpdateSize( Vector3 localChange, Direction dir )
 {
   Box box = GetShape<Box>();
   box.HalfExtents = box.HalfExtents + Vector3.Scale( GetLocalFaceDirection( dir ), localChange );
 }
Exemplo n.º 50
0
        public static void DrawWireCollider(Collider c)
        {
            if (c == null)
            {
                throw new System.ArgumentNullException("c");
            }

            if (c is BoxCollider)
            {
                var box = c as BoxCollider;
                DrawWireRectoid(box.transform.TransformPoint(box.center), box.transform.rotation, Vector3.Scale(box.size, box.transform.lossyScale));
            }
            else if (c is SphereCollider)
            {
                var sphereGeom = com.spacepuppy.Geom.Sphere.FromCollider(c as SphereCollider);
                DrawWireSphere(sphereGeom.Center, c.transform.rotation, sphereGeom.Radius);
            }
            else if (c is CapsuleCollider)
            {
                var capGeom = com.spacepuppy.Geom.Capsule.FromCollider(c as CapsuleCollider);
                DrawWireCapsule(capGeom.Start, capGeom.End, capGeom.Radius);
            }
            else if (c is CharacterController)
            {
                var capGeom = com.spacepuppy.Geom.Capsule.FromCollider(c as CharacterController);
                DrawWireCapsule(capGeom.Start, capGeom.End, capGeom.Radius);
            }
            else if (c is MeshCollider)
            {
                //not supported
                throw new System.ArgumentException("Unsupported collider type '" + c.GetType().Name + "'.", "c");
            }
            else
            {
                //not supported
                throw new System.ArgumentException("Unsupported collider type '" + c.GetType().Name + "'.", "c");
            }
        }
Exemplo n.º 51
0
    private void LegacySetParticle()
    {
        ParticleEmitter  pe = this.m_pe;
        ParticleAnimator pa = this.m_pa;
        ParticleRenderer pr = this.m_pr;

        if (pe == null || pr == null)
        {
            return;
        }
        if (this.m_bLegacyRuntimeScale)
        {
            Vector3         vector          = Vector3.get_one() * this.m_fStartSpeedRate;
            float           fStartSpeedRate = this.m_fStartSpeedRate;
            ParticleEmitter expr_53         = pe;
            expr_53.set_minSize(expr_53.get_minSize() * this.m_fStartSizeRate);
            ParticleEmitter expr_66 = pe;
            expr_66.set_maxSize(expr_66.get_maxSize() * this.m_fStartSizeRate);
            ParticleEmitter expr_79 = pe;
            expr_79.set_minEnergy(expr_79.get_minEnergy() * this.m_fStartLifeTimeRate);
            ParticleEmitter expr_8C = pe;
            expr_8C.set_maxEnergy(expr_8C.get_maxEnergy() * this.m_fStartLifeTimeRate);
            ParticleEmitter expr_9F = pe;
            expr_9F.set_minEmission(expr_9F.get_minEmission() * this.m_fStartEmissionRate);
            ParticleEmitter expr_B2 = pe;
            expr_B2.set_maxEmission(expr_B2.get_maxEmission() * this.m_fStartEmissionRate);
            pe.set_worldVelocity(Vector3.Scale(pe.get_worldVelocity(), vector));
            pe.set_localVelocity(Vector3.Scale(pe.get_localVelocity(), vector));
            pe.set_rndVelocity(Vector3.Scale(pe.get_rndVelocity(), vector));
            ParticleEmitter expr_FB = pe;
            expr_FB.set_angularVelocity(expr_FB.get_angularVelocity() * fStartSpeedRate);
            ParticleEmitter expr_10A = pe;
            expr_10A.set_rndAngularVelocity(expr_10A.get_rndAngularVelocity() * fStartSpeedRate);
            ParticleEmitter expr_119 = pe;
            expr_119.set_emitterVelocityScale(expr_119.get_emitterVelocityScale() * fStartSpeedRate);
            if (pa != null)
            {
                pa.set_rndForce(Vector3.Scale(pa.get_rndForce(), vector));
                pa.set_force(Vector3.Scale(pa.get_force(), vector));
            }
            ParticleRenderer expr_158 = pr;
            expr_158.set_lengthScale(expr_158.get_lengthScale() * this.m_fRenderLengthRate);
        }
        else
        {
            Vector3         vector2  = ((!this.m_bScaleWithTransform) ? Vector3.get_one() : pe.get_transform().get_lossyScale()) * this.m_fStartSpeedRate;
            float           num      = ((!this.m_bScaleWithTransform) ? 1f : NcTransformTool.GetTransformScaleMeanValue(pe.get_transform())) * this.m_fStartSpeedRate;
            float           num2     = ((!this.m_bScaleWithTransform) ? 1f : NcTransformTool.GetTransformScaleMeanValue(pe.get_transform())) * this.m_fStartSizeRate;
            ParticleEmitter expr_1EF = pe;
            expr_1EF.set_minSize(expr_1EF.get_minSize() * num2);
            ParticleEmitter expr_1FE = pe;
            expr_1FE.set_maxSize(expr_1FE.get_maxSize() * num2);
            ParticleEmitter expr_20D = pe;
            expr_20D.set_minEnergy(expr_20D.get_minEnergy() * this.m_fStartLifeTimeRate);
            ParticleEmitter expr_220 = pe;
            expr_220.set_maxEnergy(expr_220.get_maxEnergy() * this.m_fStartLifeTimeRate);
            ParticleEmitter expr_233 = pe;
            expr_233.set_minEmission(expr_233.get_minEmission() * this.m_fStartEmissionRate);
            ParticleEmitter expr_246 = pe;
            expr_246.set_maxEmission(expr_246.get_maxEmission() * this.m_fStartEmissionRate);
            pe.set_worldVelocity(Vector3.Scale(pe.get_worldVelocity(), vector2));
            pe.set_localVelocity(Vector3.Scale(pe.get_localVelocity(), vector2));
            pe.set_rndVelocity(Vector3.Scale(pe.get_rndVelocity(), vector2));
            ParticleEmitter expr_292 = pe;
            expr_292.set_angularVelocity(expr_292.get_angularVelocity() * num);
            ParticleEmitter expr_2A1 = pe;
            expr_2A1.set_rndAngularVelocity(expr_2A1.get_rndAngularVelocity() * num);
            ParticleEmitter expr_2B0 = pe;
            expr_2B0.set_emitterVelocityScale(expr_2B0.get_emitterVelocityScale() * num);
            if (pa != null)
            {
                pa.set_rndForce(Vector3.Scale(pa.get_rndForce(), vector2));
                pa.set_force(Vector3.Scale(pa.get_force(), vector2));
            }
            ParticleRenderer expr_2F1 = pr;
            expr_2F1.set_lengthScale(expr_2F1.get_lengthScale() * this.m_fRenderLengthRate);
        }
    }
Exemplo n.º 52
0
    protected void StartPinch()
    {
        // Only pinch if we're hovering over an object.
        if (active_object_ == null)
        {
            return;
        }

        HandModel hand_model = GetComponent <HandModel>();

        Leap.Utils.IgnoreCollisions(gameObject, active_object_.gameObject, true);
        GrabbableObject grabbable = active_object_.GetComponent <GrabbableObject>();

        // Setup initial position and rotation conditions.
        palm_rotation_       = hand_model.GetPalmRotation();
        object_pinch_offset_ = Vector3.zero;

        // If we don't center the object, find the closest point in the collider for our grab point.
        if (grabbable == null || !grabbable.centerGrabbedObject)
        {
            Vector3 delta_position = active_object_.transform.position - current_pinch_position_;

            Ray        pinch_ray = new Ray(current_pinch_position_, delta_position);
            RaycastHit pinch_hit;

            // If we raycast hits the object, we're outside the collider so grab the hit point.
            // If not, we're inside the collider so just use the pinch position.
            if (active_object_.Raycast(pinch_ray, out pinch_hit, grabObjectDistance))
            {
                object_pinch_offset_ = active_object_.transform.position - pinch_hit.point;
            }
            else
            {
                object_pinch_offset_ = active_object_.transform.position - current_pinch_position_;
            }
        }

        filtered_pinch_position_ = active_object_.transform.position - object_pinch_offset_;
        object_pinch_offset_     = Quaternion.Inverse(active_object_.transform.rotation) *
                                   object_pinch_offset_;
        rotation_from_palm_ = Quaternion.Inverse(palm_rotation_) * active_object_.transform.rotation;

        // If we can rotate the object quickly, increase max angular velocity for now.
        if (grabbable == null || grabbable.rotateQuickly)
        {
            last_max_angular_velocity_ = active_object_.GetComponent <Rigidbody>().maxAngularVelocity;
            active_object_.GetComponent <Rigidbody>().maxAngularVelocity = Mathf.Infinity;
        }

        if (grabbable != null)
        {
            // Notify grabbable object that it was grabbed.
            grabbable.OnGrab();

            if (grabbable.useAxisAlignment)
            {
                // If this option is enabled we only want to align the object axis with the palm axis
                // so we'll cancel out any rotation about the aligned axis.
                Vector3 palm_vector = grabbable.rightHandAxis;
                if (hand_model.GetLeapHand().IsLeft)
                {
                    palm_vector = Vector3.Scale(palm_vector, new Vector3(-1, 1, 1));
                }

                Vector3    axis_in_palm    = rotation_from_palm_ * grabbable.objectAxis;
                Quaternion axis_correction = Quaternion.FromToRotation(axis_in_palm, palm_vector);
                if (Vector3.Dot(axis_in_palm, palm_vector) < 0)
                {
                    axis_correction = Quaternion.FromToRotation(axis_in_palm, -palm_vector);
                }

                rotation_from_palm_ = axis_correction * rotation_from_palm_;
            }
        }
    }
Exemplo n.º 53
0
        private void Update()
        {
            transform.localScale = new Vector3(
                _parentRectTransform.sizeDelta.x / _bounds.size.x,
                _parentRectTransform.sizeDelta.y / _bounds.size.y,
                1f);
            transform.localScale = Vector3.Scale(transform.localScale, _scaleMultiplier);

            switch (_cornerAchor)
            {
            case Anchor2D.None:
                break;

            case Anchor2D.UpperLeft:
                transform.localPosition = new Vector3(
                    (-_parentRectTransform.sizeDelta.x / 2) + _offset.x,
                    (_parentRectTransform.sizeDelta.y / 2) + _offset.z,
                    _offset.z);
                break;

            case Anchor2D.Upper:
                transform.localPosition = new Vector3(
                    _offset.x,
                    (_parentRectTransform.sizeDelta.y / 2) + _offset.y,
                    _offset.z);
                break;

            case Anchor2D.UpperRight:
                transform.localPosition = new Vector3(
                    (_parentRectTransform.sizeDelta.x / 2) + _offset.x,
                    (_parentRectTransform.sizeDelta.y / 2) + _offset.y,
                    _offset.z);
                break;

            case Anchor2D.Left:
                transform.localPosition = new Vector3(
                    (-_parentRectTransform.sizeDelta.x / 2) + _offset.x,
                    _offset.y,
                    _offset.z);
                break;

            case Anchor2D.Center:
                transform.localPosition = new Vector3(
                    _offset.x,
                    _offset.y,
                    _offset.z);
                break;

            case Anchor2D.Right:
                transform.localPosition = new Vector3(
                    (_parentRectTransform.sizeDelta.x / 2) + _offset.x,
                    _offset.y,
                    _offset.z);
                break;

            case Anchor2D.Lowerleft:
                transform.localPosition = new Vector3(
                    (-_parentRectTransform.sizeDelta.x / 2) + _offset.x,
                    (-_parentRectTransform.sizeDelta.y / 2) + _offset.y,
                    _offset.z);
                break;

            case Anchor2D.Lower:
                transform.localPosition = new Vector3(
                    _offset.x,
                    (-_parentRectTransform.sizeDelta.y / 2) + _offset.y,
                    _offset.z);
                break;

            case Anchor2D.LowerRight:
                transform.localPosition = new Vector3(
                    (_parentRectTransform.sizeDelta.x / 2) + _offset.x,
                    (-_parentRectTransform.sizeDelta.y / 2) + _offset.y,
                    _offset.z);
                break;
            }
        }
 // Update is called once per frame
 void Update()
 {
     CollisionReaction();
     max = Vector3.Scale(bounds.max, transform.localScale) + transform.position;
     min = Vector3.Scale(bounds.min, transform.localScale) + transform.position;
 }
Exemplo n.º 55
0
    public void JumpTo(GameObject gao)
    {
        if (UnitySettings.IsRaymapGame)
        {
            return;
        }
        Vector3?           center = null, size = null;
        BasePersoBehaviour bpb = gao.GetComponent <BasePersoBehaviour>();

        if (bpb != null)
        {
            switch (bpb)
            {
            case PersoBehaviour pb:
                //print(pb.perso.SuperObject.boundingVolume.Center + " - " + pb.perso.SuperObject.boundingVolume.Size);
                center = (pb.perso.SuperObject != null && pb.perso.SuperObject.boundingVolume != null) ? (pb.transform.position + pb.perso.SuperObject.boundingVolume.Center) : pb.transform.position;
                size   = (pb.perso.SuperObject != null && pb.perso.SuperObject.boundingVolume != null) ? Vector3.Scale(pb.perso.SuperObject.boundingVolume.Size, pb.transform.lossyScale) : pb.transform.lossyScale;
                break;

            case ROMPersoBehaviour rpb:
                center = rpb.transform.position;
                size   = rpb.transform.lossyScale;
                break;

            case PS1PersoBehaviour ppb:
                center = ppb.transform.position;
                size   = ppb.transform.lossyScale;
                break;
            }
        }
        else
        {
            SuperObjectComponent sc = gao.GetComponent <SuperObjectComponent>();
            if (sc != null)
            {
                if (sc.so != null)
                {
                    center = (gao.transform.position + sc.so.boundingVolume.Center);
                    size   = Vector3.Scale(sc.so.boundingVolume.Size, gao.transform.lossyScale);
                }
                else
                {
                    center = gao.transform.position;
                    size   = gao.transform.lossyScale;
                }
            }
        }
        if (center.HasValue)
        {
            float objectSize   = Mathf.Min(5f, Mathf.Max(size.Value.x, size.Value.y, size.Value.z));
            bool  orthographic = cam.orthographic;
            if (orthographic)
            {
                targetOrthoSize = objectSize * 2f * 1.5f;
                Vector3 target = cam.transform.InverseTransformPoint(center.Value);
                targetPos = cam.transform.TransformPoint(new Vector3(target.x, target.y, 0f));
            }
            else
            {
                float cameraDistance = 4.0f;                                                     // Constant factor
                float cameraView     = 2.0f * Mathf.Tan(0.5f * Mathf.Deg2Rad * cam.fieldOfView); // Visible height 1 meter in front
                float distance       = cameraDistance * objectSize / cameraView;                 // Combined wanted distance from the object
                distance += objectSize;                                                          // Estimated offset from the center to the outside of the object * 2

                /*transform.position = center.Value + -transform.right * distance;
                 * transform.LookAt(center.Value, Vector3.up);*/
                //transform.LookAt(center.Value, Vector3.up);
                //transform.position = center.Value + Vector3.Normalize(transform.position - center.Value) * distance;
                targetPos = center.Value + Vector3.Normalize(transform.position - center.Value) * distance;
                if (center.Value - transform.position != Vector3.zero)
                {
                    targetRot = Quaternion.LookRotation(center.Value - transform.position, Vector3.up);
                }
            }
        }
    }
Exemplo n.º 56
0
    void Update()
    {
        // Get look input

        var dx = Input.GetAxis("Look Horizontal " + playerIndex) * control;
        var dy = Input.GetAxis("Look Vertical " + playerIndex) * control;
        var dz = Input.GetAxis("Look Roll " + playerIndex) * control;

        dx           *= dx * Mathf.Sign(dx);
        dy           *= dy * Mathf.Sign(dy);
        dz           *= dz * Mathf.Sign(dz);
        dx           += spinOutVector.x * spinOutFactor;
        dy           += spinOutVector.y * spinOutFactor;
        dz           += spinOutVector.z * spinOutFactor;
        spinOutFactor = Mathf.Max(spinOutFactor - 0.25F, 0);

        // Change the target look orientation based on the user's camera control input
        // and slowly interpolate this parent object's rotation to it based on the lookDrag

        var s = lookSpeed * Time.deltaTime * (2F + moveBoost) / 3F;

        lookTarg *= Quaternion.AngleAxis(dx * s, -Vector3.up);
        lookTarg *= Quaternion.AngleAxis(dy * s, -Vector3.forward);
        lookTarg *= Quaternion.AngleAxis(dz * s, -Vector3.right);
        transform.localRotation = Quaternion.Slerp(transform.localRotation, lookTarg, lookDrag);

        // Change the ship's look orientation as well

        s = shipLookSpeed;

        var shipLookTarg = Quaternion.identity;

        shipLookTarg *= Quaternion.AngleAxis(dx * s, -Vector3.up);
        shipLookTarg *= Quaternion.AngleAxis(dy * s, -Vector3.forward);
        shipLookTarg *= Quaternion.AngleAxis(dz * s, -Vector3.right);
        shipLook      = Quaternion.Slerp(shipLook, shipLookTarg, shipLookDrag);

        // Finally, set the position and rotation of the ship model
        // This includes a little bit of permutation for when the ship is idle

        s = Mathf.Max(0, 1 - body.velocity.magnitude * 0.05F);

        float hOff     = playerIndex * 5F;
        var   rotHover = Quaternion.identity;

        rotHover *= Quaternion.Euler(Mathf.Sin(Time.time * 2F + hOff) * 2 * s, 0, 0);
        rotHover *= Quaternion.Euler(0, Mathf.Cos(Time.time * 1.5F + hOff) * 3 * s, 0);
        rotHover *= Quaternion.Euler(0, 0, Mathf.Sin(Time.time * 2.5F + hOff) * s);
        var posHover = Vector3.zero;

        posHover.x         += Mathf.Cos(Time.time * 1.5F + hOff) * 0.03F * s;
        posHover.y         += Mathf.Sin(Time.time * 2.5F + hOff) * 0.03F * s;
        posHover.z         += Mathf.Cos(Time.time * 2F + hOff) * 0.015F * s;
        model.localPosition = posHover;

        model.rotation  = body.rotation;
        model.rotation *= shipLook;
        model.rotation *= Quaternion.Euler(0, turn, 0);
        model.rotation *= Quaternion.Euler(roll + moveBoostRoll, 0, 0);
        model.rotation *= modelRot;
        model.rotation *= rotHover;
        model.rotation *= Quaternion.Euler(spinOutFactor * 30, spinOutFactor * 30, spinOutFactor * 30);

        // Slowly center the camera over time

        camPos = Vector3.Lerp(camPos, camTargPos, camDrag * Time.deltaTime);
        camRot = Quaternion.Slerp(camRot, camTargRot, camDrag * Time.deltaTime);
        cam.transform.localPosition = camPos + new Vector3(rumble * 2F, -rumble * 0.25F, 0);
        Vector3 jitter = Random.insideUnitSphere;

        jitter.Scale(new Vector3(rumble * 0.075F, rumble * 0.075F, rumble * 0.075F));
        cam.transform.localPosition += jitter;
        cam.transform.localRotation  = camRot;

        // Rotate the armature

        armatureBase.rotation = Quaternion.identity;

        armature[0].rotation = model.rotation * Quaternion.Euler(270, 180, 0);
        for (int i = 1; i < armature.Length; i++)
        {
            float      speed       = 1 + body.velocity.magnitude * 0.2F;
            Quaternion permutation = Quaternion.Euler(Mathf.Sin(Time.time * 3F + i * 2) * speed,
                                                      Mathf.Cos(Time.time * 4F + i * 5) * speed * 2,
                                                      Mathf.Sin(Time.time * 5F + i * 7) * speed * 2);
            if (armature[i].name.Contains("_"))
            {
                permutation *= Quaternion.Euler(0, dy * -20, dx * -20);
                permutation *= Quaternion.Euler(0, 0, Mathf.DeltaAngle(turn, turnTarg));
            }
            armature[i].rotation = model.rotation * armatureRots[i] * permutation;
        }

        // Point the arrow

        arrow.pointAt(game.getCheckpointPos(playerIndex), transform.localRotation * Vector3.up);
    }
Exemplo n.º 57
0
    private void scrollChildControls( Vector3 delta )
    {
        try
        {

            scrolling = true;

            delta = delta.Scale( 1, -1, 1 );

            for( int i = 0; i < controls.Count; i++ )
            {
                var child = controls[ i ];
                child.Position = ( child.Position - delta ).RoundToInt();
            }

        }
        finally
        {
            scrolling = false;
        }
    }
Exemplo n.º 58
0
        void ApplyTransform()
        {
            // Position and rotation.
            var p = position.Vector * position.Scalar;
            var r = Quaternion.AngleAxis(rotation.Scalar, rotation.Vector);

            if (position.mode != TransformMode.Off)
            {
                if (useDifferentials)
                {
                    if (useLocalCoordinate)
                    {
                        transform.localPosition += p - previousPosition;
                    }
                    else
                    {
                        transform.position += p - previousPosition;
                    }
                }
                else
                {
                    if (useLocalCoordinate)
                    {
                        transform.localPosition = p;
                    }
                    else
                    {
                        transform.position = p;
                    }
                }
            }

            if (rotation.mode != TransformMode.Off)
            {
                if (useDifferentials)
                {
                    var dr = r * Quaternion.Inverse(previousRotation);
                    if (useLocalCoordinate)
                    {
                        transform.localRotation = dr * transform.localRotation;
                    }
                    else
                    {
                        transform.rotation = dr * transform.rotation;
                    }
                }
                else
                {
                    if (useLocalCoordinate)
                    {
                        transform.localRotation = r;
                    }
                    else
                    {
                        transform.rotation = r;
                    }
                }
            }

            previousPosition = p;
            previousRotation = r;

            // Scale.
            if (scale.mode != TransformMode.Off)
            {
                var so = useDifferentials ? initialScale : Vector3.one;
                var sc = Vector3.one + scale.Vector * (scale.Scalar - 1);
                transform.localScale = Vector3.Scale(so, sc);
            }
        }
Exemplo n.º 59
0
    // Update is called once per frame
    void Update()
    {
        if (!IsDead)
        {
            // Interact with the item
            if (mInteractItem != null && Input.GetKeyDown(KeyCode.F))
            {
                // Common interact method
                mInteractItem.OnInteract();

                // TODO: Check to move this logic to a better location
                if (mInteractItem is InventoryItemBase)
                {
                    Inventory.AddItem(mInteractItem as InventoryItemBase);
                    (mInteractItem as InventoryItemBase).OnPickup();
                }

                Hud.CloseMessagePanel();

                mInteractItem = null;
            }

            // Execute action with item
            if (mCurrentItem != null && Input.GetMouseButtonDown(0))
            {
                // TODO: Logic which action to execute has to come from the particular item
                _animator.SetTrigger("attack_1");
            }

            // Get Input for axis
            float h = Input.GetAxis("Horizontal");
            float v = Input.GetAxis("Vertical");

            // Calculate the forward vector
            Vector3 camForward_Dir = Vector3.Scale(Camera.main.transform.forward, new Vector3(1, 0, 1)).normalized;
            Vector3 move           = v * camForward_Dir + h * Camera.main.transform.right;

            if (move.magnitude > 1f)
            {
                move.Normalize();
            }

            // Calculate the rotation for the player
            move = transform.InverseTransformDirection(move);

            // Get Euler angles
            float turnAmount = Mathf.Atan2(move.x, move.z);

            transform.Rotate(0, turnAmount * RotationSpeed * Time.deltaTime, 0);

            if (_characterController.isGrounded)
            {
                _animator.SetBool("run", move.magnitude > 0);

                _moveDirection = transform.forward * move.magnitude;

                _moveDirection *= Speed;
            }

            _moveDirection.y -= Gravity * Time.deltaTime;

            _characterController.Move(_moveDirection * Time.deltaTime);
        }
    }
Exemplo n.º 60
0
        private static Transform CreateModelFrom(
            Core_Voxel.Result.VoxelNode vNode, Transform parent, Vector3 pivot,
            ref List <Mesh> meshs, ref Dictionary <Texture2D, Material> materialsMap,
            bool isRig, bool withAvatar
            )
        {
            Quaternion rot            = vNode.Rotation;
            Vector3    pivotFixOffset = rot * pivot;
            Vector3    fixedModelSize = rot * vNode.Size.ToVector3();

            pivotFixOffset.Scale(fixedModelSize);
            Vector3 scaleFix = rot * (0.5f * (Vector3.one - vNode.Scale.ToVector3()));

            scaleFix.Scale(fixedModelSize);
            pivotFixOffset -= scaleFix;

            Vector3 fixedMvPos = vNode.Position.ToVector3();

            fixedMvPos.x += Mathf.RoundToInt(fixedModelSize.x % 2f) * 0.5f;
            fixedMvPos.y += Mathf.RoundToInt(fixedModelSize.y % 2f) * 0.5f;
            fixedMvPos.z += Mathf.RoundToInt(fixedModelSize.z % 2f) * 0.5f;

            var root = new GameObject().transform;

            root.SetParent(parent);
            root.localRotation = vNode.Rotation;
            root.localScale    = vNode.Scale.ToVector3();
            root.gameObject.SetActive(vNode.Active);

            if (vNode.Model != null)
            {
                root.name          = !string.IsNullOrEmpty(vNode.Name) ? vNode.Name : GetIndexedName("Model", parent.childCount - 1);
                root.localPosition = (fixedMvPos - 0.5f * fixedModelSize + pivotFixOffset) * ModelScale;

                // Empty Check
                bool isEmpty = true;
                var  uMesh   = vNode.Model;
                if (uMesh.Count > 0)
                {
                    for (int i = 0; i < uMesh.Count; i++)
                    {
                        if (uMesh[i].vertexCount > 0)
                        {
                            isEmpty = false;
                            break;
                        }
                    }
                }

                if (!isEmpty)
                {
                    // Add Assets
                    Texture2D texture = vNode.Texture;
                    if (!texture)
                    {
                        texture = new Texture2D(4, 4);
                    }
                    Material mat = new Material(TheShader)
                    {
                        mainTexture = texture
                    };
                    materialsMap.Add(texture, mat);

                    // Add Mesh To
                    if (vNode.Model.Count == 1)
                    {
                        var mesh = vNode.Model[0];
                        if (!meshs.Contains(mesh))
                        {
                            meshs.Add(mesh);
                        }
                        AddMeshTo(mesh, root, mat, isRig);
                    }
                    else
                    {
                        for (int i = 0; i < vNode.Model.Count; i++)
                        {
                            var target = new GameObject("m_" + i.ToString()).transform;
                            target.SetParent(root);
                            target.SetAsLastSibling();
                            target.localPosition = Vector3.zero;
                            target.localRotation = Quaternion.identity;
                            target.localScale    = Vector3.one;
                            var mesh = vNode.Model[i];
                            if (!meshs.Contains(mesh))
                            {
                                meshs.Add(mesh);
                            }
                            AddMeshTo(mesh, target, mat, false);
                        }
                    }
                }
            }
            else if (vNode.Children != null && vNode.Children.Length > 0)
            {
                // Sub Objects
                root.name          = !string.IsNullOrEmpty(vNode.Name) ? vNode.Name : "Container";
                root.localPosition = vNode.Position.ToVector3() * ModelScale;
                for (int i = 0; i < vNode.Children.Length; i++)
                {
                    CreateModelFrom(vNode.Children[i], root, pivot, ref meshs, ref materialsMap, isRig, withAvatar);
                }
            }
            return(root);
        }