示例#1
2
 void Start()
 {
     ancienPos = obj.transform.position;
     posVoulu = ancienPos + vue;
     this.transform.position = posVoulu;
     y_start = transform.position.y;
 }
示例#2
2
 void Rotate(float degreesAroundRight, float degreesAroundUp)
 {
     Quaternion rotation = Quaternion.Euler(-degreesAroundRight, degreesAroundUp, 0f);
     transform.rotation = rotation;
     Vector3 percheASelfie = new Vector3(0f, 0f, -_distance); // TODO: Move new outside of update
     transform.position = rotation * percheASelfie;
 }
示例#3
1
 private void Awake()
 {
     button = transform.FindChild("Button");
     thebase = transform.FindChild("Base");
     startScale = button.localScale;
     targetScale = thebase.localScale;
 }
示例#4
1
    float CalculatePathLength(Vector3 targetPosition)
    {
        // Create a path and set it based on a target position.
        NavMeshPath path = new NavMeshPath();
        if (nav.enabled)
            nav.CalculatePath(targetPosition, path);

        // Create an array of points which is the length of the number of corners in the path + 2.
        Vector3[] allWayPoints = new Vector3[path.corners.Length + 2];

        // The first point is the enemy's position.
        allWayPoints[0] = transform.position;

        // The last point is the target position.
        allWayPoints[allWayPoints.Length - 1] = targetPosition;

        // The points inbetween are the corners of the path.
        for (int i = 0; i < path.corners.Length; i++)
        {
            allWayPoints[i + 1] = path.corners[i];
        }

        // Create a float to store the path length that is by default 0.
        float pathLength = 0;

        // Increment the path length by an amount equal to the distance between each waypoint and the next.
        for (int i = 0; i < allWayPoints.Length - 1; i++)
        {
            pathLength += Vector3.Distance(allWayPoints[i], allWayPoints[i + 1]);
        }
        return pathLength;
    }
示例#5
1
文件: Grapple.cs 项目: Deus0/Zeltex
	public bool IsHoldingGrapple = false;	// if true the player is pulled alongwith the hook shot
	public void CreateGrappleBeam() {
		if (!IsGrappling) {
			HandPosition = transform.position;	// default for now
			RaycastHit hit;
			Player MyPlayer = gameObject.GetComponent<Player> ();
			if (Physics.Raycast (transform.position, MyPlayer.ShootForwardVector, out hit, 100)) {
				HandPosition = hit.point;
				Quaternion NewRotation = new Quaternion ();
				//NewRotation.eulerAngles = (hit.point - gameObject.transform.position);
				NewRotation.eulerAngles =  MyPlayer.ShootForwardVector;
				NewRotation = Quaternion.identity;
				//Debug.LogError ("Angle of Grapple: " + NewRotation.eulerAngles.ToString());
				GameObject MyChain = (GameObject)Instantiate (GrappleBeamPrefab, HandPosition, NewRotation);
				//NewRotation = MyChain.transform.rotation;
				MyChain.transform.LookAt(hit.point);
				//Debug.LogError ("Angle of Grapple: " + MyChain.transform.rotation.eulerAngles.ToString());
				if (IsHoldingGrapple) {
					//MyChain.transform.rotation = NewRotation;
					transform.position = MyChain.transform.GetChild (7).transform.position;
					Vector3 CharacterBodyOffset = new Vector3(0,-1.5f,0);
					transform.position = transform.position+CharacterBodyOffset;
					gameObject.AddComponent<FixedJoint> ();
					gameObject.GetComponent<FixedJoint> ().connectedBody = MyChain.transform.GetChild (7).GetComponent<Rigidbody> ();
					gameObject.GetComponent<CharacterController> ().enabled = false;
					IsGrappling = true;
					gameObject.GetComponent<Rigidbody>().isKinematic = false;
				}
			}
		}
	}
示例#6
1
 // Update is called once per frame
 void Update()
 {
     offset = Vector3.Lerp(offset,Vector3.zero, 20f * Time.deltaTime);
     transform.position = Vector3.Lerp(transform.position, player.transform.position, 1.0f * Time.deltaTime);
         transform.position = new Vector3(transform.position.x,transform.position.y,-20f)+offset;
         GetComponent<Camera>().orthographicSize = Screen.height / 128f;
 }
示例#7
1
    // Update is called once per frame
    void Update()
    {
        //		transform.LookAt(transform.position + Camera.main.transform.rotation * Vector3.back,
        //            Camera.main.transform.rotation * Vector3.up);

        //glowAmmount -= RATE * Time.deltaTime;
        glowAmount = Mathf.Lerp(glowAmount, 0, RATE * Time.deltaTime);

        if(glowAmount < 0)
            glowAmount = 0;

        //Debug.Log(glowAmmount * AMMOUNT);

        //		Color c = Color.blue;
        //		c.a = Mathf.Clamp01(glowAmmount * AMMOUNT);
        //
        //		renderer.material.color = c;

        //glowAmmount = 1.0f;

        transform.LookAt(transform.position + previousVelocity);
        GetComponent<ParticleSystem>().startSpeed = transform.parent.rigidbody.velocity.magnitude;
        GetComponent<ParticleSystem>().emissionRate = glowAmount * AMOUNT - THRESHOLD;

        //particleEmitter.Emit(Vector3.zero, previousVelosity, 1, 1, Color.white);
        //particleEmitter.Emit(50);

        previousVelocity = transform.parent.rigidbody.velocity;
    }
 public static Obj_AI_Hero GetTarget(this Spell spell,
     bool ignoreShields = true,
     Vector3 from = default(Vector3),
     IEnumerable<Obj_AI_Hero> ignoredChampions = null)
 {
     return TargetSelector.GetTarget(spell, ignoreShields, from, ignoredChampions);
 }
示例#9
1
    void Update()
    {
        if (!_First && _Velocity != 0)
        {
            float smooth = (_Velocity > 0) ? SmoothRate : -SmoothRate;
            _Velocity -= smooth * Time.deltaTime;
            if (Mathf.Abs(_Velocity) < 0.01f) _Velocity = 0f;

            Vector3 move = new Vector3(_Velocity * -1, 0, 0);
            _Transform.Translate(move, Space.World);
        }

        if (Input.GetMouseButton(0))
        {
            if (!_First)
            {
                DragEnter();
                _First = true;
            }
            else
                DragUpdate();
        }
        else if (Input.GetMouseButtonUp(0))
        {
            _First = false;
        }
    }
示例#10
1
    public bool TakeDamage(int amount, Vector3 hitPoint)
    {
        // If the enemy is dead...
        if (isDead)
            // ... no need to take damage so exit the function.
            return false;

        // Play the hurt sound effect.
        //enemyAudio.Play();

        // Reduce the current health by the amount of damage sustained.
        currentHealth -= amount;
        healthPercent = Mathf.CeilToInt((currentHealth * 1.0f) / (startingHealth) * 100);
        // Set the position of the particle system to where the hit was sustained.
        //hitParticles.transform.position = hitPoint;

        // And play the particles.
        //hitParticles.Play();

        // If the current health is less than or equal to zero...
        if (currentHealth <= 0)
        {
            // ... the enemy is dead.
            Death();
            return true;
        }
        return false;
    }
    void Update()
    {
        // Get input vector from kayboard or analog stick and make it length 1 at most
        Vector3 inputVector = new Vector3(0/*Input.GetAxis("Horizontal")*/, Input.GetAxis("Vertical"), 0);
        if(1 < inputVector.magnitude) {
            inputVector = inputVector.normalized;
        }
        inputVector = inputVector.normalized * Mathf.Pow(inputVector.magnitude, 2);

        // Rotate input vector into camera space so up is camera's up and right is camera's right
        inputVector = Camera.main.transform.rotation * inputVector;

        // Rotate input vector to be perpendicular to character's up vector
        Quaternion camToCharacterSpace = Quaternion.FromToRotation(Camera.main.transform.forward*-1, transform.up);
        inputVector = (camToCharacterSpace * inputVector);

        // Make input vector relative to Character's own orientation
        inputVector = Quaternion.Inverse(transform.rotation) * inputVector;

        if(walkMultiplier!=1) {
            if( (Input.GetKey("left shift") || Input.GetKey("right shift")) != defaultIsWalk ) {
                inputVector *= walkMultiplier;
            }
        }

        //motor.desiredTurn = inputVector.x;
        //inputVector.x = 0;

        // Apply direction
        motor.desiredMovementDirection = inputVector;

        return;
    }
示例#12
1
    // Update is called once per frame
    void Update()
    {
        this.transform.position += Velocity*Time.deltaTime;

        if (transform.position.x < -384)
        {
            Velocity = new Vector3(200.0f, Velocity.y, 0);
        }

        if (transform.position.x > 384)
        {
            Velocity = new Vector3(-200.0f, Velocity.y, 0);
        }

        if (pointer.renderer.enabled == false)
        {
            if (transform.position.y > 640)
            {
                pointer.rotation = Quaternion.Euler (0, 0, 0);
                pointer.renderer.enabled = true;
                controls.p1Wins++;
                StartCoroutine("timeout");
            }
            else if (transform.position.y < -640)
            {
                pointer.rotation = Quaternion.Euler (0, 0, 180);
                pointer.renderer.enabled = true;
                controls.p2Wins++;
                StartCoroutine("timeout");
            }
        }
    }
示例#13
1
文件: Track.cs 项目: abusque/racexna
        private void SetObstacles()
        {
            string modelName = "tree stomp sculpture";
            float modelScale = 0.02f;
            Vector3 initRot = new Vector3(-MathHelper.PiOver2, 0, 0);
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(29, 0, -8) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(63, 0, -18) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(101, 0, -13) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(101, 0, -19) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(111, 0, -20) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(94, 0, -31) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(15, 0, -36) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(111, 0, -43) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(50, 0, -50) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(106, 0, -53) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(57, 0, -55) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(98, 0, -62) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(75, 0, -68) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(28, 0, -69) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(42, 0, -69) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(81, 0, -78) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(13, 0, -85) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(103, 0, -89) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(73, 0, -90) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(49, 0, -92) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(37, 0, -101) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(106, 0, -53) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(120, 0, -121) * Ground.TerrainScale, modelScale, initRot));
            Obstacles.Add(new BaseObject(RaceGame, modelName, Ground.Origin + new Vector3(24, 0, -122) * Ground.TerrainScale, modelScale, initRot));

            for (int i = 0; i < Obstacles.Count; ++i)
            {
                RaceGame.Components.Add(Obstacles[i]);
            }
        }
示例#14
1
文件: Plane.cs 项目: bradleat/trafps
 public Plane(Vector3 n, float d)
     : base((int)PrimitiveType.Plane)
 {
     JiggleMath.NormalizeSafe(ref n);
     this.normal = n;
     this.d = d;
 }
示例#15
1
 public Vector3 Add(ref Vector3 v)
 {
     return new Vector3(
         x: x + v.x,
         y: y + v.y,
         z: z + v.z);
 }
    private ScoreboardController _scoreboardController; // hold reference to ScoreboardController

    #endregion Fields

    #region Methods

    IEnumerator SpawnWaves()
    {
        yield return new WaitForSeconds(startWait);

        while (true)
        {
            for (int i = 0; i < hazardCount; i++)
            {
                Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y,
                    spawnValues.z);
                Quaternion spawnRotation = Quaternion.identity;
                // spawn with no rotation, this is already defined in RandomRotator.cs
                Instantiate(hazard, spawnPosition, spawnRotation);
                yield return new WaitForSeconds(spawnWait);
            }
            yield return new WaitForSeconds(waveWait);

            if (_scoreboardController.IsGameOver())
            {
                _scoreboardController.restartLabel.text = "Press 'R' to Restart";
                _scoreboardController.SetRestart(true);
                break;
            }
        }
    }
    public void Update()
    {
        if (Input.GetMouseButtonDown(0)
            && SpaceTraderConfig.LocalPlayer
            && SpaceTraderConfig.LocalPlayer.Ship)
        {
            var pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y);
            var ray = SpaceTraderConfig.WorldMap.Camera.ScreenPointToRay(pos);

            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, float.PositiveInfinity, LayerMask.GetMask("World Map")))
            {
                //the only things on this layer with colliders should be markers
                var mapArea = hit.collider.GetComponent<WorldMapMarker>().Area;

                SpaceTraderConfig.LocalPlayer.Ship.Target = mapArea.GetComponent<Targetable>();

                Debug.Log("targetted area " + mapArea);
            }
        }

        float eastWest = Input.GetAxis("yaw");
        float northSouth = Input.GetAxis("pitch");

        const float PAN_SPEED = 50;

        camOffset += PAN_SPEED * Time.deltaTime * new Vector3(eastWest, 0, northSouth);
        var lerped = Vector3.Lerp(mapCamera.transform.position, camOffset, 2 * Time.deltaTime);

        var camXform = mapCamera.transform;
        camXform.position = lerped;
    }
示例#18
1
	public void SelfDestructor(int combo, bool b){
		Combo.setCombo(combo);
		rotate = true;
		timer = 0f;
		randomRot = new Vector3(Random.Range(-1f, 1f), Random.Range(-1f, 0f), Random.Range(-1f, 1f));
		Destroy(gameObject, 20f);
	}
 public override void Fire(Vector3 direction, Quaternion rotation)
 {
     currentDistance = 0;
         base.Fire(direction,rotation);
                 BulletProjectileUp();
       amIFired = true;
 }
示例#20
1
        // Update is called once per frame
        private void Update()
        {
            Vector3 targetPosition = target.position;
            targetPosition.x = Mathf.Clamp(targetPosition.x, BoundsMin.x, BoundsMax.x);
            targetPosition.y = Mathf.Clamp(targetPosition.y, BoundsMin.y, BoundsMax.y);

            // only update lookahead pos if accelerating or changed direction
            float xMoveDelta = (targetPosition - m_LastTargetPosition).x;

            bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > lookAheadMoveThreshold;

            if (updateLookAheadTarget)
            {
                m_LookAheadPos = lookAheadFactor*Vector3.right*Mathf.Sign(xMoveDelta);
            }
            else
            {
                m_LookAheadPos = Vector3.MoveTowards(m_LookAheadPos, Vector3.zero, Time.deltaTime*lookAheadReturnSpeed);
            }

            Vector3 aheadTargetPos = targetPosition + m_LookAheadPos + Vector3.forward*m_OffsetZ;
            Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref m_CurrentVelocity, damping);

            transform.position = newPos;

            m_LastTargetPosition = targetPosition;
        }
示例#21
1
    void MarchingCubesGo()
    {
        MarchingCubes.SetTarget (marchingCubesThreshold);
        MarchingCubes.SetWindingOrder(2, 1, 0);
        MarchingCubes.SetModeToTetrahedrons();
        MarchingCubes.SetScalar (voxelResolution);

        Vector3 minExtantPos = Vector3.one * voxelCountPerChunk * chunkStride * -0.5f * voxelResolution;

        for (int i = 0; i < chunkStride; i++) {
            for (int j = 0; j < chunkStride; j++) {
                for (int k = 0; k < chunkStride; k++) {
                    Vector3 start = new Vector3(i, j, k);
                    Vector3 end = start + Vector3.one;
                    start *= voxelCountPerChunk;
                    if (i > 0) start.x -= 1;
                    if (j > 0) start.y -= 1;
                    if (k > 0) start.z -= 1;
                    end *= voxelCountPerChunk;
                    end -= Vector3.one;
                    Mesh msh = MarchingCubes.CreateMesh (voxels, start, end);
                    msh.uv = new Vector2[msh.vertices.Length];
                    msh.RecalculateNormals();
                    msh.RecalculateBounds();
                    GameObject go = (GameObject)Instantiate (meshPrefab);
                    go.transform.position = minExtantPos;
                    go.GetComponent<MeshFilter> ().mesh = msh;
                    go.GetComponent<MeshCollider>().sharedMesh = msh;
                }
            }
        }
    }
    // Use this for initialization
    void Start()
    {
        for (int i = 0; i < this.transform.childCount; i++) {
            GameObject obj = this.transform.GetChild(i).gameObject;
            Animator animator = obj.GetComponentInChildren<Animator>();
            this.animatorList.Add(animator);
            obj.SetActive(false);
        }

        switch (showType) {
        case ShowType.Enumeration: {
            for(int i = 0; i < animatorList.Count; i++){
                GameObject obj = animatorList[i].transform.parent.gameObject;
                obj.SetActive(true);
                float x = -20 + (i / 5) * 5;
                float y = 10 - (i % 5) * 5;
                Vector3 pos = new Vector3(x, y, i);
                obj.transform.localPosition = pos;
            }
            break;
        }
        case ShowType.Queue: {
            if(animatorList.Count >= 1){
                currentAnimator = animatorList[0];
                GameObject obj = currentAnimator.transform.parent.gameObject;
                obj.SetActive(true);
            }
            break;
        }
        }
    }
		////////////////////////////////////////////////////////////////////////////////////////////////
		/*--------------------------------------------------------------------------------------------*/
		internal void UpdateWithCursor(Vector3? pCursorPosition) {
			if ( pCursorPosition == null || vIsAnimating ) {
				HighlightProgress = 0;
				vSelectionStart = null;
				IsSelectionPrevented = false;
				return;
			}

			if ( vCursorDistanceFunc == null ) {
				throw new Exception("No CursorDistanceFunction has been set.");
			}

			if ( !NavItem.IsEnabled ) {
				HighlightDistance = float.MaxValue;
				HighlightProgress = 0;
				return;
			}

			float dist = vCursorDistanceFunc((Vector3)pCursorPosition);
			float prog = Mathf.InverseLerp(vSettings.HighlightDistanceMax,
				vSettings.HighlightDistanceMin, dist);

			HighlightDistance = dist;
			HighlightProgress = prog;
		}
示例#24
1
        /// <summary>
        /// Checks the mouse's position set in the in-game world plane.
        /// </summary>
        /// <param name="mousePosition">Mouse's position on screen</param>
        /// <param name="camera">Camera object</param>
        /// <param name="device">Graphics device used in rendering</param>
        /// <returns></returns>
        public static Vector3 getMouseWorldPosition(Vector2 mousePosition,CameraAndLights camera,GraphicsDevice device)
        {
            Vector3 nearsource = new Vector3(mousePosition,0f);
            Vector3 farsource = new Vector3(mousePosition,CameraAndLights.nearClip);

            Vector3 nearPoint = device.Viewport.Unproject(nearsource,
                                                          camera.projectionMatrix,
                                                          camera.viewMatrix,
                                                          Matrix.Identity);

            Vector3 farPoint = device.Viewport.Unproject(farsource,
                                                         camera.projectionMatrix,
                                                         camera.viewMatrix,
                                                         Matrix.Identity);

            // Create a ray from the near clip plane to the far clip plane.
            Vector3 direction = farPoint - nearPoint;
            direction.Normalize();
            Ray pickRay = new Ray(nearPoint,direction);

            Plane floor = new Plane(new Vector3(0f,1f,0f),0f);

            float denominator = Vector3.Dot(floor.Normal,pickRay.Direction);
            float numerator = Vector3.Dot(floor.Normal,pickRay.Position) + floor.D;
            float dist = -(numerator / denominator);

            Vector3 mouseWorldPos = nearPoint + direction * dist;

            return mouseWorldPos * new Vector3(1f,0f,1f);
        }
    // Update is called once per frame
    void FixedUpdate()
    {
        if (should_shoot) {
            // did shoot before?
            if (delay_active){
                // enough time in between passed?
                if (stopwatch.ElapsedMilliseconds > delay) {
                    stopwatch.Reset();
                    delay_active = false;
                }
            }else{
                // shoot
                Transform tmp = Instantiate(bullet, transform.position, Quaternion.identity) as Transform;
                GameObject spawned_bullet = tmp.gameObject;
                spawned_bullet.layer = this.gameObject.layer;

                direction = (ship.transform.position - this.transform.position).normalized;
                /*
                // add spread
                direction = new Vector3(direction.x + Random.Range(-accuarcy_spread, accuarcy_spread),
                                        direction.y + Random.Range(-accuarcy_spread, accuarcy_spread),
                                        direction.z + Random.Range(-accuarcy_spread, accuarcy_spread));
        */
                spawned_bullet.transform.rotation = Quaternion.LookRotation(direction);
                spawned_bullet.GetComponent<Rigidbody>().AddForce(direction * bullet_speed);

                stopwatch.Start();
                delay_active = true;
            }
        }
    }
示例#26
0
    // Update is called once per frame
    void FixedUpdate()
    {
        if(BallRef)
        {
            //DISTANCE
            DistanceToTarget = Vector3.Distance(transform.position, BallRef.transform.position);

            //GET MOVE TO LOCATION
            if(BallRef.GetComponent<Rigidbody>().velocity.normalized == Vector3.zero)
            {
                MoveToLocation = BallRef.position + new Vector3(0f,0f,-2.5f);
            }
            else
            {
                MoveToLocation = BallRef.position + ((BallRef.GetComponent<Rigidbody>().velocity.normalized) * -2.5f);
            }
            MoveToLocation += (Vector3.up * 2);

            //MOVE
            transform.position = Vector3.Lerp(transform.position, MoveToLocation, Time.deltaTime * (DistanceToTarget/3));

            //LOOK AT
            Vector3 relativePos = (BallRef.transform.position + Vector3.up) - transform.position;
            Quaternion rotation = Quaternion.LookRotation(relativePos);
            transform.rotation = rotation;

        }
    }
示例#27
0
文件: Plane.cs 项目: bradleat/trafps
 public Plane(Vector3 n, Vector3 pos)
     : base((int)PrimitiveType.Plane)
 {
     JiggleMath.NormalizeSafe(ref n);
     this.normal = n;
     this.d = -Vector3.Dot(n, pos);
 }
    void FixedUpdate()
    {
        //have we moved more than our minimum extent?
        Vector3 movementThisStep = myRigidbody.position - previousPosition;
        float movementSqrMagnitude = movementThisStep.sqrMagnitude;

        if (movementSqrMagnitude > sqrMinimumExtent)
        {
            float movementMagnitude = Mathf.Sqrt(movementSqrMagnitude);
            RaycastHit hitInfo;

            //check for obstructions we might have missed
            if (Physics.Raycast(previousPosition, movementThisStep, out hitInfo, movementMagnitude, layerMask.value))
            {
                if (!hitInfo.collider)
                    return;

                if (this.GetComponent<Collider>().isTrigger)
                    this.SendMessage("OnTriggerEnter", hitInfo.collider);

                if (hitInfo.collider.isTrigger)
                    hitInfo.collider.SendMessage("OnTriggerEnter", myCollider);

                if (!hitInfo.collider.isTrigger)
                    myRigidbody.position = hitInfo.point - (movementThisStep / movementMagnitude) * partialExtent;

            }
        }

        previousPosition = myRigidbody.position;
    }
示例#29
0
 public void LookAt(Vector3 destination)
 {
     float tempX = transform.rotation.eulerAngles.x;
     transform.LookAt(destination);
     // compensating mesh flaw, it's awful, but it's works
     transform.rotation = Quaternion.Euler(tempX, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);
 }
示例#30
0
    public void DrawAttkBox(SPoint[] v, string mat, int n, int endN, SPoint p, int pNum,  int t, int poly)
    {
        //specialized manual function for attackboxes
        subMesh [poly] = new Mesh ();
        int vTot = endN - n + 1;
        Vector3[] vertices = new Vector3[vTot];
        Color32[] col = new Color32[vTot];

        //std::stringstream hbName;
        string hbName = "P#" + pNum + "HB-" + t + "-" + poly;

        for (int i = n; i <= endN; i++) {
            vertices [i-n] = new Vector3 (v [i].x + p.x, v [i].y + p.y, 0);
            col [i-n] = new Color32 (0, 250, 20, 150);
        }
        int tTot = (vTot - 2) * 3;
        int[] tri = new int[tTot];
        for (int i = 0; i<(tTot/3);i++) {//triangle fan
            tri[i*3]=0;
            tri[(i*3)+1]=i+1;
            tri[(i*3)+2]=i+2;
        }
        subMesh[poly].vertices=vertices;
        subMesh[poly].triangles = tri;
        subMesh[poly].colors32 = col;
    }
示例#31
0
 void Start()
 {
     startPos  = begin.transform.position;
     moveRight = end.transform.position;
 }
示例#32
0
 void FixedUpdate()
 {
     gravityVector = GravityField.instance.GetGravity(transform.position);
     rigidbody.AddForce(gravityVector * rigidbody.mass);
 }
示例#33
0
	public void setPosition(Vector3 pos)
	{
		mPosition = new Vector3(pos.x, pos.y, pos.z);
	}
示例#34
0
 public CieLchuv(Vector3 vector)
     : this(vector, DefaultWhitePoint)
 {
 }
示例#35
0
    private void FixedUpdate()

    {
        transform.position = Vector3.Lerp(transform.position, target.position + offset, smoothSpeed * Time.deltaTime);
    }
    private void Shoot()
    {
        readyToShoot = false;

        //Find the exact hit position using a raycast
        Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)); //Just a ray through the middle of your current view
        RaycastHit hit;

        //check if ray hits something
        Vector3 targetPoint;
        if (Physics.Raycast(ray, out hit))
            targetPoint = hit.point;
        else
            targetPoint = ray.GetPoint(75); //Just a point far away from the player

        //Calculate direction from attackPoint to targetPoint
        Vector3 directionWithoutSpread = targetPoint - attackPoint.position;

        //Calculate spread
        float x = Random.Range(-spread, spread);
        float y = Random.Range(-spread, spread);

        //Calculate new direction with spread
        Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, 0); //Just add spread to last direction

        //Instantiate bullet/projectile
        GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity); //store instantiated bullet in currentBullet
        //Rotate bullet to shoot direction
        currentBullet.transform.forward = directionWithSpread.normalized;

        //Add forces to bullet
        currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
        currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * upwardForce, ForceMode.Impulse);
        if(currentBullet.gameObject.CompareTag("Enemy"))
        {
            Destroy(currentBullet.gameObject, 3);
        }
        if (currentBullet.gameObject.CompareTag("Thing"))
        {
            Destroy(currentBullet.gameObject, 3);
        }


        //Instantiate muzzle flash, if you have one
        if (muzzleFlash != null)
            Instantiate(muzzleFlash, attackPoint.position, Quaternion.identity);

        bulletsLeft--;
        bulletsShot++;

        //Invoke resetShot function (if not already invoked), with your timeBetweenShooting
        if (allowInvoke)
        {
            Invoke("ResetShot", timeBetweenShooting);
            allowInvoke = false;
            

            //Add recoil to player (should only be called once)
            playerRb.AddForce(-directionWithSpread.normalized * recoilForce, ForceMode.Impulse);
        }

        //if more than one bulletsPerTap make sure to repeat shoot function
        if (bulletsShot < bulletsPerTap && bulletsLeft > 0)
            Invoke("Shoot", timeBetweenShots);
    }
示例#37
0
 public void MovementFunction(float x, float y)
 {
     var camDir = new Vector3(cam.transform.forward.x, 0, cam.transform.forward.z);
     transform.localPosition += camDir * y * Time.deltaTime * speed;
     transform.localPosition += cam.transform.right * x * Time.deltaTime * speed;
 }
示例#38
0
    public void Dropa1()

    {
        float Distance = Vector3.Distance(a1.transform.position, a1Black.transform.position);



        if (Distance < 50)
        {
            a1.transform.position = a1Black.transform.position;



            source.clip = correct;
            source.Play();

            count++;
            time_now2 = System.DateTime.Now;
            Debug.Log(time_now2);


            diff = time_now2 - time_now;
            Debug.Log(diff);


            timef = diff.ToString(@"hh\:mm");
            Debug.Log(timef);


            timef = diff.ToString(@"hh\:mm");
            Debug.Log(timef);


            conn   = "URI=file:" + Application.dataPath + "/Plugins/grad.s3db";
            dbconn = (IDbConnection) new SqliteConnection(conn);
            dbconn.Open();
            IDbCommand dbcmd = dbconn.CreateCommand();

            IDbCommand dbcmd2 = dbconn.CreateCommand();

            IDbCommand dbcmd3 = dbconn.CreateCommand();


            string tableName = String.Concat(str, str2);


            Debug.Log(tableName);



            if (count1 == 0)
            {
                string sqlQuery = @" insert into " + tableName + "(milkQT,milkQR,milkFailed) values ('" + timef + "','" + corr + "','" + count1 + "')";
                Debug.Log(sqlQuery);
                dbcmd.CommandText = sqlQuery;
                dbcmd.ExecuteNonQuery();

                Panel.SetActive(true);
            }

            else
            {
                string sqlQuery6 = @" insert into " + tableName + "(milkQT,milkQR,milkFailed) values ('" + timef + "','" + ncorr + "','" + count1 + "')";
                Debug.Log(sqlQuery6);
                dbcmd3.CommandText = sqlQuery6;
                dbcmd3.ExecuteNonQuery();


                string countt1 = count1.ToString();


                txt.text = countt1;
                Panelc.SetActive(true);
            }
        }



        else
        {
            a1.transform.position = a1InitiPos;

            source.clip = incorrect;
            source.Play();
        }
    }
示例#39
0
		public override void PlaceBlock(Level world, Player player, BlockCoordinates targetCoordinates, BlockFace face, Vector3 faceCoords)
		{
			ItemBlock itemBlock = new ItemBlock(BlockFactory.GetBlockById(142));
			itemBlock.PlaceBlock(world, player, targetCoordinates, face, faceCoords);
		}
示例#40
0
        /// <summary>
        /// Spawns a copy of a vehicle.
        /// </summary>
        /// <param name="coordinates">Position of the new vehicle</param>
        /// <param name="heading">Heading of the new vehicle</param>
        /// <param name="oldVeh">Vehicle to copy</param>
        /// <returns>New vehicle handle</returns>
        public static GTA.Vehicle SpawnCopyVehicle(Vector3 coordinates, float heading, GTA.Vehicle oldVeh)
        {
            GTA.Vehicle veh = GTA.World.CreateVehicle(oldVeh.Model, coordinates, heading);

            try
            {
                // Plate
                veh.NumberPlate = oldVeh.NumberPlate;
                veh.NumberPlateType = oldVeh.NumberPlateType;

                // Wheels
                veh.WheelType = oldVeh.WheelType;

                // Mods
                bool customTire1 = Function.Call<bool>(Hash.GET_VEHICLE_MOD_VARIATION, oldVeh, 23);
                bool customTire2 = Function.Call<bool>(Hash.GET_VEHICLE_MOD_VARIATION, oldVeh, 24);  // Bike only

                if (Function.Call<int>(Hash.GET_NUM_MOD_KITS, oldVeh) != 0)
                {
                    veh.InstallModKit();

                    foreach (VehicleMod mod in Enum.GetValues(typeof(VehicleMod)))
                    {
                        if (mod == VehicleMod.FrontWheels)
                            veh.SetMod(VehicleMod.FrontWheels, oldVeh.GetMod(VehicleMod.FrontWheels), Function.Call<bool>(Hash.GET_VEHICLE_MOD_VARIATION, oldVeh, 23));
                        else if (mod == VehicleMod.BackWheels)
                            veh.SetMod(VehicleMod.FrontWheels, oldVeh.GetMod(VehicleMod.FrontWheels), Function.Call<bool>(Hash.GET_VEHICLE_MOD_VARIATION, oldVeh, 24));
                        else
                            veh.SetMod(mod, oldVeh.GetMod(mod), false);
                    }
                    foreach (VehicleToggleMod mod in Enum.GetValues(typeof(VehicleToggleMod)))
                        veh.ToggleMod(mod, oldVeh.IsToggleModOn(mod));
                    
                }
                veh.WindowTint = oldVeh.WindowTint;

                // Tire's smoke color
                veh.TireSmokeColor = oldVeh.TireSmokeColor;
                veh.CanTiresBurst = oldVeh.CanTiresBurst;

                // Neons
                foreach (VehicleNeonLight neon in Enum.GetValues(typeof(VehicleNeonLight)))
                    veh.SetNeonLightsOn(neon, oldVeh.IsNeonLightsOn(neon));

                // Color
                veh.ClearCustomPrimaryColor();
                veh.ClearCustomSecondaryColor();

                if (oldVeh.IsPrimaryColorCustom)
                    veh.CustomPrimaryColor = oldVeh.CustomPrimaryColor;
                if (oldVeh.IsSecondaryColorCustom)
                    veh.CustomSecondaryColor = oldVeh.CustomSecondaryColor;

                veh.PrimaryColor = oldVeh.PrimaryColor;
                veh.SecondaryColor = oldVeh.SecondaryColor;
                veh.PearlescentColor = oldVeh.PearlescentColor;
                veh.RimColor = oldVeh.RimColor;
                veh.DashboardColor = oldVeh.DashboardColor;
                veh.TrimColor = oldVeh.TrimColor;

                // Convertible
                // 0 -> up ; 1->lowering down ; 2->down ; 3->raising up
                if (oldVeh.IsConvertible)
                    veh.RoofState = oldVeh.RoofState;

                // Extra
                for (int i = 1; i < 15; i++)
                    veh.ToggleExtra(i, oldVeh.IsExtraOn(i));
                
                // Liveries
                veh.Livery = oldVeh.Livery;
                SetVehicleLivery2(veh, GetVehicleLivery2(oldVeh));

                // Misc
                veh.NeedsToBeHotwired = false;
                veh.IsStolen = false;
            }
            catch (Exception e)
            {
                Console.Write("Error: SpawnCopyVehicle - " + e.Message);
            }

            return veh;
        }
示例#41
0
 // Get z halfway point
 public void Start()
 {
     startPos = rb.transform.position;
     goalPos = goal.transform.position;
     halfwayPos = (goalPos - startPos) / 2;
 }
示例#42
0
	void Update () {
		transform.position = Vector3.Lerp (transform.position, Target.position + Offset, Smoothness * Time.deltaTime);

		transform.LookAt (Target);
	}
示例#43
0
 private void LookingForward() //Just looking at the target
 {
     Vector3 direction = pointNow.position - transform.position; //Vector from enemy to target
     transform.rotation = Quaternion.LookRotation(Vector3.forward, direction);
 }
示例#44
0
    //private Vector3 zoomOffset = new Vector3(10, 1, -1);
    //public float smoothTime = 0.3F;
    //private Vector3 camVel = Vector3.zero;

    //private float csTextH;
    //private float csTextW;
    //bool rShoulder;

    void Start()
    {
        offset = transform.position - casterHead.transform.position;
        //rShoulder = true;
    }
示例#45
0
 // Use this for initialization
 void Start()
 {
     originalPosition = transform.position;
     originalRotation = transform.rotation;
 }
示例#46
0
 public static Vector3 RandomCircleXZ(float range = 1f)
 {
     Vector3 random = RandomSphere(range);
     return new Vector3(random.x, 0f, random.z);
 }
示例#47
0
 public static bool Equal(Vector3 a, Vector3 b)
 {
     return(Equal(a.X, b.X) && Equal(a.Y, b.Y) && Equal(a.Z, b.Z));
 }
示例#48
0
 public static Vector3 AlongCamera(Vector2 vec, Camera camera)
 {
     Vector3 cameraForward = Vector3.Scale(camera.transform.forward, new Vector3(1, 0, 1)).normalized;
     Vector3 cameraVec = cameraForward * vec.y + camera.transform.right * vec.x;
     return cameraVec;
 }
示例#49
0
 public Action_RotateTowards(Vector3 position, float angleRange)
 {
     targetPosition = position;
     AngleRange     = angleRange;
 }
示例#50
0
 void Update() {
     if (controller.isGrounded) {
         movementVector = Vector3.Lerp(movementVector, Vector3.zero, 0.5f * Time.deltaTime);
     }
     flightState();
 }
示例#51
0
 public CieLchuv(Vector3 vector, CieXyz whitePoint)
     : this()
 {
     this.backingVector = vector;
     this.WhitePoint = whitePoint;
 }
示例#52
0
	// Generic Constructor
	public Message(string userID, string type, Vector3 pos, float verti, float hori, int time, Vector3 mov, Quaternion rot)
	{
		mUserID = userID;
		mType = type;
		mPosition = new Vector3 (pos.x, pos.y, pos.z);
		mVerticDir = verti;
		mHoriDir = hori;
		mTime = time;
		mMovement = new Vector3 (mov.x, mov.y, mov.z);
		mRotation = new Quaternion (rot.x, rot.y, rot.z, rot.w);
	}
示例#53
0
    void Update()
    {
        PlayerLocation = Player.transform.position;
        Timer         += Time.deltaTime;
        CurLocation    = Enemy.transform.position;
        CurRotation    = Enemy.transform.rotation;

        if (Timer > TimeLimit && (gameObject.tag == "Red Egg" || gameObject.tag == "Green Egg" || gameObject.tag == "Slick or Sam"))
        {
            MoveDirection = Random.Range(0, 2);
            //Move Down and Left
            if (MoveDirection == 1)
            {
                Enemy.transform.Translate(0, -1, -1);
                Timer = 0;
                //Moves++;
                //print("moves left");
            }
            //Move Down and Right
            if (MoveDirection == 0)
            {
                Enemy.transform.Translate(1, -1, 0);
                Timer = 0;
                //Moves++;
                //print("moves right");
            }
            //print(Moves);
        }
        if (Timer > TimeLimit && gameObject.tag == "Purple Egg")
        {
            MoveDirection = Random.Range(0, 2);

            //Move Down and Left
            if (MoveDirection == 1 && Moves < TotalMoves)
            {
                Enemy.transform.Translate(0, -1, -1);
                Timer = 0;
                Moves++;
                //print("moves left");
            }
            //Move Down and Right
            if (MoveDirection == 0 && Moves < TotalMoves)
            {
                Enemy.transform.Translate(1, -1, 0);
                Timer = 0;
                Moves++;
                //print("moves right");
            }
            if (Moves == TotalMoves)
            {
                CoilyTime += Time.deltaTime;
                if (CoilyTime >= CoilySpawn)
                {
                    Instantiate(Coily, CurLocation, CurRotation);
                    print("instantiated");
                    Destroy(gameObject);
                }
            }
            //print(Moves);
        }
        if (Timer > TimeLimit && gameObject.tag == "Wrong Way")
        {
            MoveDirection = Random.Range(0, 2);
            //Move Down and Left
            if (MoveDirection == 1)
            {
                Enemy.transform.Translate(1, 0, 1);
                Timer = 0;
                //Moves++;
                //print("moves left");
            }
            //Move Down and Right
            if (MoveDirection == 0)
            {
                Enemy.transform.Translate(0, 1, 1);
                Timer = 0;
                //Moves++;
                //print("moves right");
            }
            //print(Moves);
        }
        if (Timer > TimeLimit && gameObject.tag == "Ugg")
        {
            MoveDirection = Random.Range(0, 2);
            //Move Down and Left
            if (MoveDirection == 1)
            {
                Enemy.transform.Translate(-1, 1, 0);
                Timer = 0;
                //Moves++;
                //print("moves left");
            }
            //Move Down and Right
            if (MoveDirection == 0)
            {
                Enemy.transform.Translate(-1, 0, -1);
                Timer = 0;
                //Moves++;
                //print("moves right");
            }
            //print(Moves);
        }
        if (Timer > TimeLimit && gameObject.tag == "Coily")
        {
            MoveDirection = Random.Range(0, 4);
            Distance      = transform.position - PlayerLocation;
            //print(Distance);
            //Move Up and Right
            if (Distance.y <= -1 && Distance.z <= -1)
            {
                Enemy.transform.Translate(0, 1, 1);
                Timer = 0;
                print("moves up and right");
            }
            //Move Up and Left
            else if (Distance.x >= 1 && Distance.y <= -1)
            {
                Enemy.transform.Translate(-1, 1, 0);
                Timer = 0;
                print("moves up and left");
            }
            //Move Down and Right
            else if (Distance.x <= -1 && Distance.y >= 1)
            {
                Enemy.transform.Translate(0, -1, 1);
                Timer = 0;
                print("moves down and right");
            }
            //Move Down and Left
            else if (Distance.y >= 1 && Distance.z >= 1)
            {
                Enemy.transform.Translate(0, -1, -1);
                Timer = 0;
                print("moves down and left");
            }
            else if (CurLocation == PlayerLocation)
            {
                Object.Destroy(gameObject);
            }
            else
            {
                //Move Up and Right
                if (MoveDirection == 0)
                {
                    Enemy.transform.Translate(0, 1, 1);
                    Timer = 0;
                    print("moves randomly up and right");
                }
                //Move Up and Left
                if (MoveDirection == 1)
                {
                    Enemy.transform.Translate(-1, 1, 0);
                    Timer = 0;
                    print("moves randomly up and left");
                }
                //Move Down and Right
                if (MoveDirection == 2)
                {
                    Enemy.transform.Translate(0, -1, 1);
                    Timer = 0;
                    print("moves randomly down and right");
                }
                //Move Down and Left
                if (MoveDirection == 3)
                {
                    Enemy.transform.Translate(0, -1, -1);
                    Timer = 0;
                    print("moves randomly down and left");
                }
            }
            //print(Moves);
        }
    }
示例#54
0
    void OnMouseDrag()
    {
        if (isFreezed || Game.IsOver)
        {
            return;
        }

        isGrabbed = true;
        Game.Objectives["Grab"] = true;

        if (Input.GetMouseButton(1))
        {
            //Cursor.lockState = CursorLockMode.Locked;
            rb.useGravity      = false;
            rb.velocity        = Vector3.zero;
            rb.angularVelocity = Vector3.zero;
            float   hInput         = Input.GetAxis("Mouse X");
            float   vInput         = Input.GetAxis("Mouse Y");
            float   h              = horizontalSpeed * hInput;
            float   v              = verticalSpeed * vInput;
            Vector3 horizontalAxis = Vector3.zero;
            Vector3 verticalAxis   = Vector3.zero;
            Vector3 cameraPos      = Camera.main.transform.position;
            float   x              = cameraPos.x;
            float   z              = cameraPos.z;

            if (x > z && x + z < 0)
            {
                horizontalAxis = Vector3.back;
                verticalAxis   = Vector3.right;
            }
            else if (x < z && x + z < 0)
            {
                horizontalAxis = Vector3.left;
                verticalAxis   = Vector3.back;
            }
            else if (x < z && x + z > 0)
            {
                horizontalAxis = Vector3.forward;
                verticalAxis   = Vector3.left;
            }
            else if (x > z && x + z > 0)
            {
                horizontalAxis = Vector3.right;
                verticalAxis   = Vector3.forward;
            }


            if (Input.GetKey(KeyCode.LeftControl))
            {
                rotationDelay -= Time.deltaTime;

                if (rotationDelay <= 0)
                {
                    //transform.rotation = transform.rotation.AlignToRightAngles();

                    if (vInput > 0.5 || vInput < -0.5)
                    {
                        transform.RotateAround(handle.transform.position, verticalAxis, 90 * Mathf.Sign(vInput));

                        rotationDelay = 0.2f;
                    }
                    if (hInput > 0.5 || hInput < -0.5)
                    {
                        transform.RotateAround(handle.transform.position, horizontalAxis, 90 * Mathf.Sign(hInput));

                        rotationDelay = 0.2f;
                    }
                }
            }
            else
            {
                transform.RotateAround(handle.transform.position, verticalAxis, v);
                transform.RotateAround(handle.transform.position, horizontalAxis, h);
            }
        }
        else
        {
            rb.useGravity = true;
            Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
            Vector3 destination   = Camera.main.ScreenToWorldPoint(mousePosition);

            rb.velocity = (destination - handle.transform.position) * currentSensitivity;
        }
    }
示例#55
0
 void IEffect.Bind(int index, Transform trans, Vector3 offset, EEffectBindType bindType, int time, Vector3 normal)
 {
     if (bindType == EEffectBindType.Local)
     {
         this.transform.SetParent(trans);
         this.transform.localPosition = Vector3.zero + offset;
     }
     else if (bindType == EEffectBindType.Origin)
     {
         this.transform.SetParent(null);
         this.transform.position = stageOriginPosition + offset;
     }
     else
     {
         if (trans != null)
         {
             this.transform.SetParent(null);
             this.transform.position = trans.position + offset;
         }
     }
     if (direction == EEffectDirection.forward)
     {
         this.transform.rotation = Quaternion.LookRotation(normal, trans.up);
     }
     else if (direction == EEffectDirection.backward)
     {
         this.transform.rotation = Quaternion.LookRotation(normal * -1, trans.up);
     }
     EffectManager.Free(this, time, ((IEffect)this).group, OnFree);
 }
 // Start is called before the first frame update
 void Start()
 {
     // Herhaalt de achtergrond dmv boxcolliders.
     startPos = transform.position;
     repeatWidth = GetComponent<BoxCollider>().size.x / 2;
 }
示例#57
0
        public bool Hit(DamageData damageData)
        {
            var speed = ObjectController.Speed;
            
            // 强制位移
             Vector3 forcedOffset = Vector3.zero;
            
            // 击退
            var selfObjectController = ObjectController;
            var selfHitAndMat = selfObjectController as HitAble;

            var otherObjectController = damageData.hitGameObject.GetComponent<IObjectController>();
            var otherHurtAble = damageData.hitGameObject.GetComponent<HurtAble>();
            
            
            if (otherObjectController != null && otherObjectController.CanRebound)
            {
                if (otherObjectController.IsDefending)
                {
                    Vector3 moveBySpeed = (damageData.targetMoveBy * (-otherObjectController.DefenseRepellingResistance)).MoveByToSpeed();
                    if (ObjectController.Speed.magnitude < moveBySpeed.magnitude)
                    {
                        // 去除y方向的反弹效果 add by TangJian 2019/1/26 17:19
                        speed.x = moveBySpeed.x;
                        speed.z = moveBySpeed.z;
                    }
                }
                else
                {
                    Vector3 moveBySpeed = (damageData.targetMoveBy * (-otherObjectController.RepellingResistance)).MoveByToSpeed();
                    if (speed.magnitude < moveBySpeed.magnitude)
                    {
                        // 去除y方向的反弹效果 add by TangJian 2019/1/26 17:19
                        speed.x = moveBySpeed.x;
                        speed.z = moveBySpeed.z;
                    }
                }
                
                // 强制位移 add by TangJian 2019/4/30 10:29
                if(damageData.useForcedOffset && otherObjectController is RoleController)
                {
                    forcedOffset = CalcOffset(selfObjectController, otherObjectController, damageData.forcedOffset);
                }
            }

            if (otherObjectController.IsGrounded())
            {
                
            }

            if (otherHurtAble != null && selfHitAndMat != null)
            {
                // 攻击击中时动画暂停
                AnimSuspend(damageData.selfSuspendTime, 1f + (damageData.selfSuspendScale - 1f) * otherHurtAble.Damping);
                
                Vector3 rendererOffset = Vector3.zero;
                if (damageData.effectOrientation.z > 0)
                {
                    rendererOffset.z = otherObjectController.BackZ;
                }
                else
                {
                    rendererOffset.z = otherObjectController.FrontZ;
                }

                Vector3 worldPos;
                if (otherHurtAble.TryGetHitPos(out worldPos))
                {
                    // 打击特效
                    BothAnimManager.Instance.PlayHitEffect(selfHitAndMat.GetHitEffectType(), otherHurtAble.GetMatType(), worldPos + rendererOffset + forcedOffset, damageData.direction.x > 0 ? Direction.Right : Direction.Left, damageData.effectOrientation.GetAngleZ());
                }
                else
                {
                    switch (otherHurtAble.EffectShowMode)
                    {
                        case EffectShowMode.FrontOrBack :
                            BothAnimManager.Instance.PlayHitEffect(selfHitAndMat.GetHitEffectType(), otherHurtAble.GetMatType(), new Vector3(damageData.collidePoint.x, damageData.collidePoint.y, otherObjectController.transform.position.z) + rendererOffset + forcedOffset, damageData.direction.x > 0 ? Direction.Right : Direction.Left, damageData.effectOrientation.GetAngleZ());
                            break;
                        case EffectShowMode.ColliderPoint:
                            BothAnimManager.Instance.PlayHitEffect(selfHitAndMat.GetHitEffectType(), otherHurtAble.GetMatType(), damageData.collidePoint + forcedOffset, damageData.direction.x > 0 ? Direction.Right : Direction.Left, damageData.effectOrientation.GetAngleZ());
                            break;
                        default:
                            BothAnimManager.Instance.PlayHitEffect(selfHitAndMat.GetHitEffectType(), otherHurtAble.GetMatType(), damageData.collidePoint + forcedOffset, damageData.direction.x > 0 ? Direction.Right : Direction.Left, damageData.effectOrientation.GetAngleZ());
                            break;
                    }
                } 
                AudioManager.Instance.PlayEffect(selfHitAndMat.GetHitEffectType(),otherHurtAble.GetMatType(), worldPos + rendererOffset + forcedOffset);
            }

            selfObjectController.Speed = speed;
            return true;
        }
示例#58
0
        Vector3 CalcOffset(IObjectController selfObjectController, IObjectController otherObjectController, Vector3 offset)
        {
            Vector3 forcedOffset = Vector3.zero;

            var otherToSelfOffset = selfObjectController.transform.position - otherObjectController.transform.position;

            if (Mathf.Abs(otherToSelfOffset.x) < Mathf.Abs(offset.x))
            {
                forcedOffset = otherToSelfOffset + new Vector3(offset.x * selfObjectController.GetDirectionInt(), offset.y, offset.z);
            }
                    
            forcedOffset.y = 0;
            forcedOffset.z = 0;
            
            return forcedOffset;
        }
示例#59
0
    // Use this for initialization
    IEnumerator Start()
    {
        PersistentStorage.init();
        ReadImagetargetPosition.init();
        list = PersistentStorage.findForImageTargetId(gameObject.name);
        currentImagetargetInfo = ReadImagetargetPosition.findForImageTargetPosition(gameObject.name);
        allImagetargetInfo     = ReadImagetargetPosition.getAllImagetargerPositionInfo();
        foreach (Row row in list)
        {
            Vector3 shrinkedPos = new Vector3(row.localPosition.x / 3.0f,
                                              row.localPosition.y / 3.0f,
                                              row.localPosition.z / 3.0f);
            Vector3    position    = transform.TransformPoint(shrinkedPos);
            Quaternion rotation    = transform.rotation * row.localRotation;
            GameObject videoPlayer = Instantiate(videoPlayerPrefab, transform);
            videoPlayerList.Add(videoPlayer);
            videoPlayer.transform.position = position;
            videoPlayer.transform.rotation = rotation;
            GameObject videoPlane = videoPlayer.transform.Find("VideoPlane").gameObject;
            TextMesh   videoName  = videoPlayer.transform.Find("VideoName").GetComponent <TextMesh>();
            videoName.text = row.videoPath;
            VideoPlayer player = videoPlane.GetComponent <VideoPlayer>();
            player.url = Application.persistentDataPath + "/" + row.videoPath;
            Debug.LogFormat("Row: {0} {1}", row.imageTargetId, row.videoPath);
            player.Play();
            timelineController.rowVideoList.Add(new RowVideoPair(row, videoPlayer));
        }

        foreach (ImagetargetPositionInfo info in allImagetargetInfo)
        {
            if (info.imageTargetId == this.gameObject.name)
            {
                initPos = new Vector3(info.x, info.y, info.z);
                arrows.Add(null);
                arrowsToOriginDistance.Add(0.0f);
                Debug.LogFormat("Image Target: {0} Pos: {1}", info.imageTargetId, initPos);
            }
            else
            {
                GameObject newArrow     = GameObject.Instantiate(arrowPrefab, transform);
                TextMesh   pointedImage = newArrow.transform.Find("pointedImage").GetComponent <TextMesh>();
                pointedImage.text = info.imageTargetId;
                float distance = Vector3.Distance(transform.position, newArrow.transform.position);
                arrows.Add(newArrow);
                arrowsToOriginDistance.Add(distance);
            }
        }
        Vector3 curPos = transform.position;

        for (int i = 0; i < allImagetargetInfo.Count; i++)
        {
            if (arrows [i] != null)
            {
                float radians = Mathf.Atan2(initPos.z - allImagetargetInfo[i].z, initPos.x - allImagetargetInfo[i].x);
                arrows[i].transform.eulerAngles = new Vector3(0, radians * 180 / Mathf.PI, 0);
                arrows[i].transform.position    = new Vector3(curPos.x - arrowsToOriginDistance[i] * Mathf.Cos(radians),
                                                              arrows[i].transform.position.y,
                                                              curPos.z - arrowsToOriginDistance[i] * Mathf.Sin(radians));
            }
        }
        yield return(new WaitForSeconds(1f));        //wait the first frame to show up

        foreach (GameObject videoPlayer in videoPlayerList)
        {
            GameObject  videoPlane = videoPlayer.transform.Find("VideoPlane").gameObject;
            VideoPlayer player     = videoPlane.GetComponent <VideoPlayer>();
            player.Pause();
            int videoWidth  = player.texture.width;
            int videoHeight = player.texture.height;
            Debug.LogFormat("Video width: {0} height: {1}", videoWidth, videoHeight);
            videoPlane.transform.localScale = new Vector3(videoPlane.transform.localScale.x,
                                                          videoPlane.transform.localScale.y,
                                                          videoPlane.transform.localScale.z * videoHeight / videoWidth);
        }
    }
    void Update()
    {
        if (PauseMenu.IsOn)
        {
            if (Cursor.lockState != CursorLockMode.None)
            {
                Cursor.lockState = CursorLockMode.None;
            }

            motor.Move(Vector3.zero);
            motor.Rotate(Vector3.zero);
            motor.RotateCamera(0f);

            return;
        }


        if (Cursor.lockState != CursorLockMode.Locked)
        {
            Cursor.lockState = CursorLockMode.Locked;
        }

        //Calculate how high the player should float above ground
        RaycastHit _hit;

        if (Physics.Raycast(transform.position, Vector3.down, out _hit, 100f, environmentMask))
        {
            joint.targetPosition = new Vector3(0f, -_hit.point.y, 0f);
        }
        else
        {
            joint.targetPosition = new Vector3(0f, 0f, 0f);
        }

        //calculate movement velocity as a 3D vector
        float xMov = Input.GetAxisRaw("Horizontal");
        float zMov = Input.GetAxisRaw("Vertical");

        Vector3 movHorizontal = transform.right * xMov;
        Vector3 movVertical   = transform.forward * zMov;

        //Final Movement Vector
        Vector3 _velocity = (movHorizontal + movVertical).normalized * speed;

        //Apply movement
        //Takes our velocity above and sends it to motor script
        motor.Move(_velocity);

        //Calculate rotation as a 3D vector
        //Lets us turn the player with the mouse
        float yRot = Input.GetAxisRaw("Mouse X");

        Vector3 _rotation = new Vector3(0f, yRot, 0f) * horizontalSensitivity;

        //Apply rotation
        motor.Rotate(_rotation);

        //Calculate camera rotation as a 3D vector
        //Lets us turn the camera with the mouse
        float xRot = Input.GetAxisRaw("Mouse Y");

        float _cameraRotationX = xRot * verticalSensitivity;

        //Apply rotation
        motor.RotateCamera(_cameraRotationX);

        //Calculate thruster force based on input
        Vector3 _thrusterForce = Vector3.zero;

        if (Input.GetButton("Jump") && thrusterFuelAmount > 0f)
        {
            thrusterFuelAmount -= thrusterFuelBurnSpeed * Time.deltaTime;

            if (thrusterFuelAmount >= 0.02f)
            {
                _thrusterForce = Vector3.up * thrusterForce;
                SetJointSettings(0f);
            }
        }
        else
        {
            thrusterFuelAmount += thrsuterFuelRegenSpeed * Time.deltaTime;

            SetJointSettings(jointSpring);
        }

        thrusterFuelAmount = Mathf.Clamp(thrusterFuelAmount, 0f, 1f);

        //Apply Thruster Force
        motor.ApplyThruster(_thrusterForce);
    }