public void SetAbsoluteTarget(Vector3 absoluteTarget) { m_mode = AimingMode.TARGET; m_aimTarget = null; m_relativeTarget = absoluteTarget; Update(); }
public void SetTargetWorldPos(Vector3 worldPos) { targetWorldPos = worldPos; var viewportPos = Camera.main.WorldToViewportPoint(targetWorldPos.Value); _CachedTransform.position = UICamera.currentCamera.ViewportToWorldPoint(viewportPos); }
public void SetAbsoluteTarget(Vector3 absoluteTarget) { m_followMovement = false; m_aimTarget = null; m_relativeTarget = absoluteTarget; Update(); }
public void SetTarget(MyEntity entity, Vector3? relativeTarget = null) { m_mode = AimingMode.TARGET; m_aimTarget = entity; m_relativeTarget = relativeTarget; Update(); }
public void PlayerLocationUpdated(BlockPosition newPos) { Node goalNode = new Node(); goalNode.pos = newPos; if(playerLocation.Equals(newPos)) return; else playerLocation = newPos; _positionsToGo.Clear(); BlockPosition currPos = getCoordinates(); Node startNode = new Node(); startNode.pos = currPos; datastructures.PriortyQueue<Node> Pqueue = new datastructures.PriortyQueue<Node>(Search.ManhattanDistance, goalNode); List<BlockPosition> path = Search.getInstance().GraphSearch(startNode, goalNode, GameManager.Instance.MazeInfo, Pqueue); print("Monster location =" + currPos.row + " , " + currPos.column); currentDestination = null; foreach (BlockPosition n in path) //put all waypoints into array { _positionsToGo.Push(getBlockCoordinates(n)); } }
public void SetTarget(MyEntity entity, Vector3? relativeTarget = null) { m_followMovement = false; m_aimTarget = entity; m_relativeTarget = relativeTarget; Update(); }
public override void Update() { float dist = speed * Time.deltaTime; Rect touchArea = new Rect(Screen.width - 50, Screen.height - 50, 50, 50); //right up corner if(Input.touchCount == 0) { moveMotion = null; } else { Touch t = Input.touches[0]; if (touchArea.Contains(t.position)) { moveMotion = playerManager.transform.rotation * Vector3.forward * dist; } else { moveMotion = null; } } if(moveMotion != null) { moveMotion = new Vector3(moveMotion.Value.x, 0, moveMotion.Value.z); } base.Update (); }
void readInput(string controlScheme) { switch (controlScheme) { case "RTSmouse": if(Input.GetMouseButtonDown(1)){ RTSmouseMovement(Input.mousePosition); velocity = velocity.normalized * speed * Time.deltaTime; //Debug.Log(destination.Value); } if(destination.HasValue) { //Debug.Log (velocity + " " + destination.Value); bool pointReached = rb.moveTo(destination.Value, velocity, speed); if(pointReached) { destination = null; //Debug.Log(rb.position); } } break; case "RTSkey": break; case "RTSmousekey": break; case "thirdperson": break; } }
public override void Update() { //remote? if (RemoteSensorClient.Instance != null && RemoteSensorClient.Instance.OrientationEnabled) { Vector3 sensorAngles = RemoteSensorClient.Instance.CameraAngles; eulerAngles = new Vector3(-sensorAngles.x, -sensorAngles.y, 0); rotation = null; } else { if(!Input.GetMouseButton(0)) { rotation = null; eulerAngles = null; return; } x = playerManager.transform.eulerAngles.y; y = playerManager.transform.eulerAngles.x; x += Input.GetAxis ("Mouse X") * xSpeed * 0.02f; y -= Input.GetAxis ("Mouse Y") * ySpeed * 0.02f; //y = clampAngle (y, yMinLimit, yMaxLimit); rotation = Quaternion.Euler (y, x, 0); } base.Update (); }
void Update() { if (master != null) { //cloning operations if (IsCloningTranslation) { transform.position = master.transform.position; } if (IsCloningRotation) { transform.rotation = master.transform.rotation; } if (IsCloningScale) { transform.localScale = master.transform.localScale; } if (!mMasterLastPosition.HasValue) { mMasterLastPosition = master.transform.position; } if (!mMasterLastRotation.HasValue) { mMasterLastRotation = master.transform.eulerAngles; } if (!mMasterLastScale.HasValue) { mMasterLastScale = master.transform.localScale; } //shadowing operations if (IsShadowingTranslation) { Vector3 actualTransform = master.transform.position; Vector3 delta = actualTransform - (Vector3)mMasterLastPosition; transform.position += delta; mMasterLastPosition = actualTransform; } if (IsShadowingRotation) { const float unityEulerAngleThreshold = 359.5f; Vector3 actualEulerRotation = master.transform.eulerAngles; Vector3 delta = actualEulerRotation - (Vector3)mMasterLastRotation; transform.eulerAngles += new Vector3(delta.x % unityEulerAngleThreshold, delta.y % unityEulerAngleThreshold, delta.z % unityEulerAngleThreshold); mMasterLastRotation = actualEulerRotation; } if (IsShadowingScale) { Vector3 actualLocalScale = master.transform.localScale; Vector3 delta = actualLocalScale - (Vector3)mMasterLastScale; transform.localScale += delta; mMasterLastScale = actualLocalScale; } } }
public void Throw(Vector3 direction, PlayerCamera camera, PlayerCamera otherCamera, float delay) { if (direction != new Vector3(0.0f, 1.0f, 0.0f) && direction != new Vector3(0.0f, -1.0f, 0.0f)) throw new System.Exception(); if (delay > 0.0f) { delayedDirection = direction; delayedCamera = camera; delayedOtherCamera = otherCamera; throwDelayCountdown = delay; } else { DisableActor(); floatDirection = direction * blockThrowSpeed; if(camera != null) originCamera = camera.camera; if(otherCamera != null) destinationCamera = otherCamera.camera; if (throwAnimation.Length != 0) PlayAnimation(throwAnimation); collider.isTrigger = true; passedThroughSomething = false; } }
private void FollowToRoutePosition(MySmallShipBot bot) { // Fly to visible position, if too close look for new visible position if (Vector3.DistanceSquared(m_followPosition.Value, bot.GetPosition()) < 5 * 5) { m_followPosition = null; } else { bot.Move(m_followPosition.Value, m_followPosition.Value, bot.WorldMatrix.Up, false, 1, 2); if (m_stuckTimer > STUCK_TIME) { if (Vector3.DistanceSquared(bot.GetPosition(), m_stuckPosition) > STUCK_DISTANCE) { m_followPosition = null; } else { m_followPosition = m_stuckPosition + MyMwcUtils.GetRandomVector3Normalized() * 1000; } } else if (Vector3.DistanceSquared(bot.GetPosition(), m_stuckPosition) > STUCK_DISTANCE) { ResetStuck(bot); } else { m_stuckTimer += MyConstants.PHYSICS_STEP_SIZE_IN_SECONDS; } } }
public void Initialize(Vector3 direction, Vector3 position, float lifeTime, float speed) { this.direction = direction; this.startPos = position; this.lifeTime = lifeTime; this.speed = speed; }
// Update is called once per frame void Update() { //listen for key if (Input.GetKeyDown ("x")) { if (oldAV.HasValue) { this.rigidbody.angularVelocity = (Vector3) oldAV; oldAV = null; } else { oldAV = rigidbody.angularVelocity; this.rigidbody.angularVelocity = new Vector3(0,0,0); } } else if (Input.GetKeyDown ("r")) { this.rigidbody.rotation = new Quaternion(0,0,0,1); this.rigidbody.angularVelocity = new Vector3(0,0,0); } else if (Input.GetKeyDown (KeyCode.LeftArrow)) { float f = rigidbody.angularVelocity.y; this.rigidbody.angularVelocity = new Vector3(0, f + .2f,0); } else if (Input.GetKeyDown (KeyCode.RightArrow)) { float f = rigidbody.angularVelocity.y; this.rigidbody.angularVelocity = new Vector3(0,f-.2f,0); } else if (Input.GetKeyDown (KeyCode.DownArrow)) { float f = rigidbody.angularVelocity.x; this.rigidbody.angularVelocity = new Vector3(f - .2f,0,0); } else if (Input.GetKeyDown (KeyCode.UpArrow)) { float f = rigidbody.angularVelocity.x; this.rigidbody.angularVelocity = new Vector3(f + .2f,0,0); } }
/// <summary> /// Returns the best hiding spot in the current Context /// </summary> public void GetBestHidingSpot() { float distanceToClosestObstacle = float.MaxValue; foreach (SceneEntity obstacle in Context.Keys) { if (obstacle == AutonomousAgent.ParentObject) continue; float distAway = obstacle.WorldBoundingSphere.Radius + DistanceFromObstacle; Vector3 toObstacle = Vector3.Normalize(AutonomousAgent.Position - Hunter.Position); Vector3 hidingSpot = (toObstacle*distAway) + AutonomousAgent.Position; float distance = Vector3.DistanceSquared(hidingSpot, AutonomousAgent.Position); if (distance < distanceToClosestObstacle) { distanceToClosestObstacle = distance; _bestHidingSpot = hidingSpot; } } }
public SensoryInfo(Vector3 position, Vector3? direction, System.DateTime time, int sightingCount) { this.sensorCount = sightingCount; this.position = position; this.direction = direction; this.lastSighting = time; }
public override void Close() { DiffuseColor = null; ColorMaskHSV = null; base.Close(); }
void FixedUpdate() { if (_movementInput != null) { _characterFSM.Move(_movementInput.GetValueOrDefault()); _movementInput = null; } }
public override void Close() { base.Close(); ClipmapId = uint.MaxValue; AtmosphereWaveLenghts = null; PrunningFunc = null; }
public void SetTrackedObject(Entity entity) { if (entity != null && trackedTransform != entity.transform) { trackedTransform = entity.transform; trackedPosition = null; } }
public override void Play(GameObject target) { if (_isRelative) { if (_isLocal) { if (!_startPosition.HasValue) { _startPosition = target.transform.localPosition; } target.transform.localPosition = _startPosition.Value + _position.Variance(_variance); } else { if (!_startPosition.HasValue) { _startPosition = target.transform.position; } target.transform.position = _startPosition.Value + _position.Variance(_variance); } } else { if (_isLocal) { target.transform.localPosition = _position.Variance(_variance); } else { target.transform.position = _position.Variance(_variance); } } }
public Track(string id, Vector3 down, Vector3? startDir, XmlTrackNode[] nodes) { Id = id; Nodes = nodes; Down = down; StartDir = startDir; }
/// <summary> /// Defines the closest obstacle /// </summary> public void DetectClosestObstacle() { float closestObstacleDistance = float.MaxValue; _closestObstacle = null; var localAgentMatrix = Matrix.Invert(AutonomousAgent.ParentObject.World); foreach (SceneEntity obstacle in Context.Keys) { Vector3 localPos = Vector3.Transform(obstacle.World.Translation, localAgentMatrix); if (UseLineOfSight) { if (localPos.Z > 0f) continue; } float expandedRadius = obstacle.WorldBoundingSphere.Radius + AutonomousAgent.ParentObject.WorldBoundingSphere.Radius - AllowedPenetration; var ray = new Ray(Vector3.Zero, Vector3.Forward); float? result = ray.Intersects(new BoundingSphere(localPos, expandedRadius)); if (result.HasValue && result.Value < closestObstacleDistance) { closestObstacleDistance = result.Value; _closestObstacle = obstacle; _closestObstacleLocalPosition = localPos; } } }
public void UpdateZoomPosition(Vector3 position1, Vector3 position2) { _targetPosition = new Vector3(position1.x, position1.y, transform.position.z); var dist = Vector3.Distance(position1, position2); _targetOrthographicSize = dist; _targetOrthographicSize = Mathf.Clamp(_targetOrthographicSize, zoomMinSize, zoomMaxSize); }
public void SetTrackedObject(Transform target) { if (target != trackedTransform) { trackedTransform = target; trackedPosition = null; } }
public void SetTrackedObject(GameObject target) { if(target != null && target.transform != trackedTransform) { trackedTransform = target.transform; trackedPosition = null; } }
// Update is called once per frame void LateUpdate() { var mousePosn = Input.mousePosition; var mouseBtn = Input.GetMouseButton (0); if (mouseBtn) { if (lastMousePosition.HasValue) { // we are moving from here var lastPosn = this.transform.position; var targetPosn = target.transform.position; // we have traced out this distance on a sphere from lastPosn /* var rotation = TrackBall( lastMousePosition.Value.x, lastMousePosition.Value.y, mousePosn.x, mousePosn.y ); */ var rotation = FigureOutAxisAngleRotation(lastMousePosition.Value, mousePosn); var vecPos = (targetPosn - lastPosn).normalized * -distance; this.transform.position = rotation * vecPos + targetPosn; this.transform.LookAt(targetPosn); lastMousePosition = mousePosn; } else { lastMousePosition = mousePosn; } } else { lastMousePosition = null; } }
// This method realy initiates/starts the missile // IMPORTANT: Direction vector must be normalized! public void Start( Vector3 position, Vector3 initialVelocity, Vector3 direction, float impulseMultiplier, MyEntity owner) { if (Physics.Static) { Physics.Static = false; } base.Start(position, initialVelocity, direction, impulseMultiplier, owner, MyTextsWrapper.Get(MyTextsWrapperEnum.RemoteCameraHud)); Physics.AngularDamping = 1; Health = MaxHealth; m_directionAfterContact = null; var ownerShip = owner as MySmallShip; if (ownerShip != null) { ownerShip.Config.BackCamera.SetOn(); ownerShip.AddRemoteCamera(this); ownerShip.SelectLastRemoteCamera(); } }
private void WalkTorwardDst() { if (dst == null) return; Vector3 pos = transform.position; var d = dst.Value - transform.position; if (d.magnitude > 0) { transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(d), TURN_SPEED*Time.deltaTime*360); } d.Normalize(); var speed = roarActivated ? RUN_SPEED : WALK_SPEED; var dist = Time.deltaTime * speed * Mathf.Max(0, Vector3.Dot(d, transform.forward)); if (d.magnitude <= dist) { pos = dst.Value; dst = null; } else { pos += dist * transform.forward; } if (dstTimeout != null) { dstTimeout -= Time.deltaTime; if (dstTimeout.Value <= 0) { dst = null; dstTimeout = null; roarActivated = false; } } var destOnWater = TileRenderer.OnWaterTile(pos.x, pos.z); if (!destOnWater) { transform.position = pos; } }
public RobotMessage(MessageType type, string message, LabelHandle target, Vector3 targetPos, Vector3? velocity) { this.type = type; this.message = message; this.target = target; this.targetPos = targetPos; this.targetVelocity = velocity; }
public static void CreateConstrainedBillboard(ref Vector3 objectPosition, ref Vector3 cameraPosition, ref Vector3 rotateAxis, Vector3?cameraForwardVector, Vector3?objectForwardVector, out Matrix result) { throw new NotImplementedException(); }
/// <summary> /// Instantiate an instance of ExampleProximityPlayer /// </summary> /// <returns> /// A local instance of ExampleProximityPlayerBehavior /// </returns> /// <param name="index">The index of the ExampleProximityPlayer prefab in the NetworkManager to Instantiate</param> /// <param name="position">Optional parameter which defines the position of the created GameObject</param> /// <param name="rotation">Optional parameter which defines the rotation of the created GameObject</param> /// <param name="sendTransform">Optional Parameter to send transform data to other connected clients on Instantiation</param> public ExampleProximityPlayerBehavior InstantiateExampleProximityPlayer(int index = 0, Vector3?position = null, Quaternion?rotation = null, bool sendTransform = true) { if (ExampleProximityPlayerNetworkObject.Length <= index) { Debug.Log("Prefab(s) missing for: ExampleProximityPlayer. Add them at the NetworkManager prefab."); return(null); } var go = Instantiate(ExampleProximityPlayerNetworkObject[index]); var netBehavior = go.GetComponent <ExampleProximityPlayerBehavior>(); NetworkObject obj = null; if (!sendTransform && position == null && rotation == null) { obj = netBehavior.CreateNetworkObject(Networker, index); } else { metadata.Clear(); if (position == null && rotation == null) { byte transformFlags = 0x1 | 0x2; ObjectMapper.Instance.MapBytes(metadata, transformFlags); ObjectMapper.Instance.MapBytes(metadata, go.transform.position, go.transform.rotation); } else { byte transformFlags = 0x0; transformFlags |= (byte)(position != null ? 0x1 : 0x0); transformFlags |= (byte)(rotation != null ? 0x2 : 0x0); ObjectMapper.Instance.MapBytes(metadata, transformFlags); if (position != null) { ObjectMapper.Instance.MapBytes(metadata, position.Value); } if (rotation != null) { ObjectMapper.Instance.MapBytes(metadata, rotation.Value); } } obj = netBehavior.CreateNetworkObject(Networker, index, metadata.CompressBytes()); } go.GetComponent <ExampleProximityPlayerBehavior>().networkObject = (ExampleProximityPlayerNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return(netBehavior); }
public NetworkCameraBehavior InstantiateNetworkCameraNetworkObject(int index = 0, Vector3?position = null, Quaternion?rotation = null, bool sendTransform = true) { var go = Instantiate(NetworkCameraNetworkObject[index]); var netBehavior = go.GetComponent <NetworkCameraBehavior>(); var obj = netBehavior.CreateNetworkObject(Networker, index); go.GetComponent <NetworkCameraBehavior>().networkObject = (NetworkCameraNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return(netBehavior); }
public async Task <bool> UpdateCharacterPosition(uint id, Vector3?position = null, Vector3?rotation = null) { var character = await Context.Characters.FirstOrDefaultAsync(c => c.Id == id); if (character == null) { return(false); } if (position.HasValue) { character.Position = position.Value; } if (rotation.HasValue) { character.Rotation = rotation.Value; } return(await Context.SaveChangesAsync() > 0); }
public SoundChannel(Sound sound, float gain, Vector3?position, float near, float far, string category, bool muffle = false) { Sound = sound; IsStream = sound.Stream; streamSeekPos = 0; reachedEndSample = false; startedPlaying = true; mutex = new object(); ALSourceIndex = sound.Owner.AssignFreeSourceToChannel(this); if (ALSourceIndex >= 0) { if (!IsStream) { AL.BindBufferToSource(sound.Owner.GetSourceFromIndex(ALSourceIndex), 0); ALError alError = AL.GetError(); if (alError != ALError.NoError) { throw new Exception("Failed to reset source buffer: " + AL.GetErrorString(alError)); } if (!AL.IsBuffer(sound.ALBuffer)) { throw new Exception(sound.Filename + " has an invalid buffer!"); } uint alBuffer = sound.Owner.GetCategoryMuffle(category) || muffle ? sound.ALMuffledBuffer : sound.ALBuffer; AL.BindBufferToSource(sound.Owner.GetSourceFromIndex(ALSourceIndex), alBuffer); alError = AL.GetError(); if (alError != ALError.NoError) { throw new Exception("Failed to bind buffer to source (" + ALSourceIndex.ToString() + ":" + sound.Owner.GetSourceFromIndex(ALSourceIndex) + "," + sound.ALBuffer.ToString() + "): " + AL.GetErrorString(alError)); } AL.SourcePlay(sound.Owner.GetSourceFromIndex(ALSourceIndex)); alError = AL.GetError(); if (alError != ALError.NoError) { throw new Exception("Failed to play source: " + AL.GetErrorString(alError)); } } else { AL.BindBufferToSource(sound.Owner.GetSourceFromIndex(ALSourceIndex), (uint)sound.ALBuffer); ALError alError = AL.GetError(); if (alError != ALError.NoError) { throw new Exception("Failed to reset source buffer: " + AL.GetErrorString(alError)); } AL.Source(sound.Owner.GetSourceFromIndex(ALSourceIndex), ALSourceb.Looping, false); alError = AL.GetError(); if (alError != ALError.NoError) { throw new Exception("Failed to set stream looping state: " + AL.GetErrorString(alError)); } streamBuffers = new uint[4]; for (int i = 0; i < 4; i++) { AL.GenBuffer(out streamBuffers[i]); alError = AL.GetError(); if (alError != ALError.NoError) { throw new Exception("Failed to generate stream buffers: " + AL.GetErrorString(alError)); } if (!AL.IsBuffer(streamBuffers[i])) { throw new Exception("Generated streamBuffer[" + i.ToString() + "] is invalid!"); } } Sound.Owner.InitStreamThread(); } } this.Position = position; this.Gain = gain; this.Looping = false; this.Near = near; this.Far = far; this.Category = category; }
private static BlockCoordinates?FindRandomTargetBlock(Entity entity, int dxz, int dy, Vector3?targetDirectinon = null) { Random random = entity.Level.Random; BlockCoordinates coords = (BlockCoordinates)entity.KnownPosition; double currentWeight = 0; Block currentBlock = null; for (int i = 0; i < 10; i++) { int x = random.Next(2 * dxz + 1) - dxz; int y = random.Next(2 * dy + 1) - dy; int z = random.Next(2 * dxz + 1) - dxz; var blockCoordinates = new BlockCoordinates(x, y, z) + coords; var block = entity.Level.GetBlock(blockCoordinates); var blockDown = entity.Level.GetBlock(blockCoordinates + BlockCoordinates.Down); if (blockDown.IsSolid) { double weight = CalculateBlockWeight(entity, block, blockDown); if (weight > currentWeight) { currentWeight = weight; currentBlock = block; } } } return(currentBlock?.Coordinates); }
/// <summary> /// Creates a new Transform that is a copy of this one, but with the specified parameters overridden with new values. /// </summary> /// <remarks> /// Example usage: /// <code> /// Translation t = new Translation(Vector3.ONE * 2f, Quaternion.IDENTITY, new Vector3(10f, -3f, 1f)); /// Translation fiveMetresForward = t.With(translation: t.Translation + Vector3.FORWARD * 5f); /// Translation originalScale = t.With(scale: Vector3.ONE); /// Translation upsideDown = t.With(rotation: Quaternion.FromAxialRotation(Vector3.FORWARD, MathUtils.PI)); /// </code> /// </remarks> /// <param name="scale">The new scale. Leave as <c>null</c> to use the current <see cref="Scale"/>.</param> /// <param name="rotation">The new rotation. Leave as <c>null</c> to use the current <see cref="Rotation"/>.</param> /// <param name="translation">The new translation. Leave as <c>null</c> to use the current <see cref="Translation"/>.</param> /// <returns>A new Transform with the same properties as this one, except where parameters have been specified and overridden.</returns> public Transform With(Vector3?scale = null, Quaternion?rotation = null, Vector3?translation = null) { return(new Transform(scale ?? Scale, rotation ?? Rotation, translation ?? Translation)); }
public void Update(Component_Pathfinding pathfinding, float delta, double distanceToReach, Vector3 from, Vector3 target) { //wait before last path find if (updateRemainingTime > 0) { updateRemainingTime -= delta; if (updateRemainingTime < 0) { updateRemainingTime = 0; } } ////already on target position? //if( ( from.ToVector2() - target.ToVector2() ).LengthSquared() < // reachDestinationPointDistance * reachDestinationPointDistance && // Math.Abs( from.Z - target.Z ) < reachDestinationPointZDifference ) //{ // Clear(); // return; //} //clear path when target position was updated if (path != null && (foundPathForTargetPosition.Value - target).Length() > updatePathWhenTargetPositionHasChangedMoreThanDistance) { Clear(); } //clear path when unit goaway from path if (path != null && currentIndex > 0) { var previous = path[currentIndex - 1]; var next = path[currentIndex]; var min = Math.Min(previous.Z, next.Z); var max = Math.Max(previous.Z, next.Z); var projectedPoint = MathAlgorithms.ProjectPointToLine(previous.ToVector2(), next.ToVector2(), from.ToVector2()); var distanceXY = (from.ToVector2() - projectedPoint).Length(); if (distanceXY > maxAllowableDeviationFromPath || from.Z + reachDestinationPointZDifference < min || from.Z - reachDestinationPointZDifference > max) { Clear(); } } //check if need update path if (path == null && updateRemainingTime == 0) { var context = new Component_Pathfinding.FindPathContext(); context.Start = from; context.End = target; //!!!! ////public double StepSize = 0.5; ////public double Slop = 0.01; ////public Vector3 PolygonPickExtents = new Vector3( 2, 2, 2 ); //////public int MaxPolygonPath = 512; ////public int MaxSmoothPath = 2048; //////public int MaxSteerPoints = 16; //var found = pathfinding.FindPath( from, target, stepSize, polygonPickExtents, maxPolygonPath, maxSmoothPath, maxSteerPoints, out path ); pathfinding.FindPath(context); if (!string.IsNullOrEmpty(context.Error)) { Log.Warning(context.Error); } if (context.Path != null) { path = context.Path; foundPathForTargetPosition = target; currentIndex = 0; //can't find new path during specified time. updateRemainingTime = 0.3f; } else { path = null; foundPathForTargetPosition = null; currentIndex = 0; //can't find new path during specified time. updateRemainingTime = 1.0f; } } //progress if (path != null) { Vector3 point; while (true) { point = path[currentIndex]; if ((from.ToVector2() - point.ToVector2()).LengthSquared() < reachDestinationPointDistance * reachDestinationPointDistance && Math.Abs(from.Z - point.Z) < reachDestinationPointZDifference) { //reach point currentIndex++; if (currentIndex == path.Length) { //path is ended Clear(); break; } } else { break; } } } }
public static Tweener DOLookAt(this Transform target, Vector3 towards, float duration, AxisConstraint axisConstraint = AxisConstraint.None, Vector3?up = default(Vector3?)) { TweenerCore <Quaternion, Vector3, QuaternionOptions> tweenerCore = DOTween.To(() => target.rotation, delegate(Quaternion x) { target.rotation = x; }, towards, duration).SetTarget(target).SetSpecialStartupMode(SpecialStartupMode.SetLookAt); tweenerCore.plugOptions.axisConstraint = axisConstraint; tweenerCore.plugOptions.up = ((!up.HasValue) ? Vector3.up : up.Value); return(tweenerCore); }
public override SoundChannel Play(Vector3?position, float gain, bool muffle = false) { throw new InvalidOperationException(); }
public static Vector3 Get3DCirclePoint(float angle, float radius, Vector3 center, Vector3 normal, Vector3?refPoint = null) { float xv = Mathf.Cos(angle); float yv = Mathf.Sin(angle); if (refPoint == null) { refPoint = findV(normal).Value; } Vector3 w = Vector3.Cross(refPoint.Value, normal); // Return center + r * (V * cos(a) + W * sin(a)) Vector3 r1 = radius * (refPoint.Value * xv); Vector3 r2 = radius * (w * yv); return(new Vector3(center.x + r1.x + r2.x, center.y + r1.y + r2.y, center.z + r1.z + r2.z)); }
public static T Instantiate <T>(this Transform transform, T prefab, Vector3?position = null, Quaternion?rotation = null, Vector3?scale = null) where T : Component { Vector3 pos = position ?? transform.position; Quaternion rot = rotation ?? Quaternion.identity; T newObject = GameObject.Instantiate(prefab, pos, rot) as T; if (newObject != null) { newObject.name = prefab.name; if (scale.HasValue) { newObject.transform.localScale = scale.Value; } newObject.transform.SetParent(transform); } return(newObject); }
void PopNextLocation() { currentTarget = path.Pop(); }
/// <summary> /// Resets the state of the source previous position. /// </summary> public virtual void ResetPreviousState() { previousSourcePosition = null; }
public void UpdateCentroidMovement(Vector3?[] positions, float[] strengths = null, bool drawDebug = false) { if (strengths != null && positions.Length != strengths.Length) { throw new InvalidOperationException( "positions and strengths Indexables must have the same Count."); } bool[] useableIndices = new bool[_lastPositions.Length]; _didCentroidAppear = false; _didCentroidDisappear = false; int numLastValidPositions = CountValid(_lastPositions); int numCurValidPositions = CountValid(positions); if (numLastValidPositions == 0 && numCurValidPositions > 0) { _didCentroidAppear = true; } if (numLastValidPositions > 0 && numCurValidPositions == 0) { _didCentroidDisappear = true; } // Useable indices have valid positions in both the "last" and "current" arrays. for (int i = 0; i < _lastPositions.Length; i++) { if (i >= positions.Length) { break; } var lastV = _lastPositions[i]; var curV = positions[i]; if (lastV.HasValue && curV.HasValue) { useableIndices[i] = true; } else if (!lastV.HasValue && !curV.HasValue) { // One index has a value in one array and no value in the other; // this means the Centroid is going to teleport. _didCentroidTeleport = true; } } _isMoving = false; _avgDelta = Vector3.zero; int count = 0; for (int i = 0; i < useableIndices.Length; i++) { if (useableIndices[i]) { _isMoving = true; var addedDelta = (positions[i] - _lastPositions[i]).Value; if (strengths != null) { addedDelta *= strengths[i]; } _avgDelta += addedDelta; count++; } } if (count > 0) { _avgDelta /= count; } // Update centroid state. if (_didCentroidAppear) { _centroid = positions.Query() .Select(maybeV => maybeV.GetValueOrDefault()) .Fold((acc, v) => acc + v) / numCurValidPositions; if (drawDebug) { DebugPing.Ping(_centroid.Value, LeapColor.cyan, 0.20f); } } if (_centroid != null) { _centroid += _avgDelta; if (drawDebug) { DebugPing.Ping(_centroid.Value, LeapColor.green, 0.15f); } } if (_didCentroidDisappear) { if (drawDebug) { DebugPing.Ping(_centroid.Value, LeapColor.black, 0.20f); } _centroid = null; } // Set last positions with the current positions. for (int i = 0; i < _lastPositions.Length; i++) { if (i >= positions.Length) { _lastPositions[i] = null; } else { _lastPositions[i] = positions[i]; } } }
public static GameObject InstantiateGameObject(this Transform transform, GameObject prefab, Vector3?position = null, Quaternion?rotation = null, Vector3?scale = null) { Vector3 pos = position ?? transform.position; Quaternion rot = rotation ?? Quaternion.identity; GameObject newObject = GameObject.Instantiate(prefab, pos, rot) as GameObject; if (newObject != null) { newObject.name = prefab.name; if (scale.HasValue) { newObject.transform.localScale = scale.Value; } newObject.transform.parent = transform; } return(newObject); }
static public void drawCircle(Vector3 center, float radius, Color?color, Quaternion?q, Vector3?scale) { if (initCircle_g == false) { // 単位円作成 for (int i = 0; i < 24; ++i) { circle_g[i].x = Mathf.Cos(2.0f * Mathf.PI * (float)i / 24); circle_g[i].z = Mathf.Sin(2.0f * Mathf.PI * (float)i / 24); circle_g[i].y = 0.0f; } } Color c = color ?? Color.white; Quaternion lq = q ?? Quaternion.identity; Vector3 sc = scale ?? Vector3.one; Gizmos.color = c; Vector3 s = lq * (radius * Vector3Util.mul(circle_g[0], sc)) + center; for (int i = 1; i <= 24; ++i) { Vector3 e = lq * (radius * Vector3Util.mul(circle_g[i % 24], sc)) + center; Gizmos.DrawLine(s, e); s = e; } }
private void OnMouseUp(SceneView sceneView, Event e) { if (ignoreNextMouseUp) { // Double click just occurred, so don't process the up event ignoreNextMouseUp = false; return; } // if the user stopped holding shift we cancel the automatic height. if (!e.shift) { startedSubtract = false; } UpdateCSGMode(e); if (selectingHeight) { if (drawMode == DrawMode.RectangleBase) { CreateBrush(GetRectanglePoints()); } else { CreateBrush(hitPoints); } selectingHeight = false; ResetTool(); sceneView.Repaint(); } else { if (drawMode == DrawMode.RectangleBase) { if (Is3DView && !startedSubtract) { // Verify that it will form a valid prism by trying to create a polygon out the base if (IsPrismBaseValid(GetRectanglePoints())) { selectingHeight = true; prismHeight = 0; } else { // Will not form a valid prism so cancel the draw ResetTool(); sceneView.Repaint(); } } else { CreateBrush(GetRectanglePoints()); ResetTool(); sceneView.Repaint(); } } else if (drawMode == DrawMode.Ambiguous || drawMode == DrawMode.PolygonBase) { Vector3?hitPoint = GetHitPoint(e.mousePosition); if (hitPoint.HasValue) { drawMode = DrawMode.PolygonBase; hitPoints.Add(hitPoint.Value); if (hitPoints.Count > 2 && hitPoint.Value.EqualsWithEpsilon(hitPoints[0])) { if (Is3DView && !startedSubtract) { // Verify that it will form a valid prism by trying to create a polygon out the base if (IsPrismBaseValid(hitPoints)) { selectingHeight = true; prismHeight = 0; } else { // Will not form a valid prism so cancel the draw ResetTool(); sceneView.Repaint(); } } else { CreateBrush(hitPoints); ResetTool(); sceneView.Repaint(); } } } } } }
public void Reset() { Points.Clear(); TargetValid = false; Destination = null; }
public override bool Draw(Batcher2D batcher, Point position, Vector3?hue = null) { return(batcher.Draw2D(_texture, new Rectangle(position.X, position.Y, Width, Height), ShaderHuesTraslator.GetHueVector(0, false, IsTransparent ? Alpha : 0, false))); }
private static AIHeroClient GetNewTarget(float range, DamageType dmgType = DamageType.Physical, Vector3?_from = null) { if (range == -1) { range = Utility.GetAARange(); } if (ConfigMenu.OnlyAttackSelected) { if (SelectedTarget != null) { if (SelectedTarget.IsValidTarget(range)) { return(SelectedTarget); } if (SelectedTarget.IsValidTarget()) { return(null); } } } if (ConfigMenu.FocusSelected) { if (SelectedTarget != null) { if (SelectedTarget.IsValidTarget(range)) { return(SelectedTarget); } if (ConfigMenu.FocusExtraRange > 0 && SelectedTarget.IsValidTarget(range + ConfigMenu.FocusExtraRange)) { return(null); } } } var from = _from ?? ObjectManager.Player.ServerPosition; var enemies = HeroManager.Enemies.Where( p => p.IsValidTarget(range + p.BoundingRadius, true, from) && !IsInvulnerable(p, dmgType)); if (enemies.Count() == 0) { return(null); } switch (ConfigMenu.TargettingMode) { case 1: return(enemies.MinOrDefault(hero => hero.Health)); case 2: return(enemies.MaxOrDefault(hero => hero.BaseAttackDamage + hero.FlatPhysicalDamageMod)); case 3: return(enemies.MaxOrDefault(hero => hero.BaseAbilityDamage + hero.FlatMagicDamageMod)); case 4: return (enemies.MinOrDefault( hero => (_from ?? ObjectManager.Player.ServerPosition).Distance( hero.ServerPosition, true))); case 5: return(enemies.Find(hero => hero.Distance(Game.CursorPos, true) < 22500)); // 150 * 150 case 6: return (enemies.MaxOrDefault( hero => ObjectManager.Player.CalcDamage(hero, DamageType.Physical, 100) / (1 + hero.Health) * GetPriority(hero))); case 7: return (enemies.MaxOrDefault( hero => ObjectManager.Player.CalcDamage(hero, DamageType.Magical, 100) / (1 + hero.Health) * GetPriority(hero))); case 0: { var killableWithAA = enemies.Where(p => p.Health <= AutoAttack.GetDamage(p, true)).FirstOrDefault(); if (killableWithAA != null) { return(killableWithAA); } var possibleTargets = enemies.OrderByDescending(GetPriority); if (possibleTargets.Count() == 1) { return(possibleTargets.First()); } if (possibleTargets.Count() > 1) { var killableTarget = possibleTargets.OrderByDescending(GetTotalADAPMultipler) .FirstOrDefault(q => GetHealthMultipler(q) >= 10); if (killableTarget != null) { return(killableTarget); } var targets = possibleTargets.OrderBy(p => ObjectManager.Player.Distance(p.ServerPosition)); AIHeroClient mostImportant = null; double mostImportantsDamage = 0; foreach (var target in targets) { var dmg = target.CalcDamage(ObjectManager.Player, DamageType.Physical, 100) + target.CalcDamage(ObjectManager.Player, DamageType.Magical, 100); if (mostImportant == null) { mostImportant = target; mostImportantsDamage = dmg; } else { if (Utility.InAARange(ObjectManager.Player, target) && !Utility.InAARange(ObjectManager.Player, mostImportant)) { mostImportant = target; mostImportantsDamage = dmg; } else if ((Utility.InAARange(ObjectManager.Player, target) && Utility.InAARange(ObjectManager.Player, mostImportant)) || (!Utility.InAARange(ObjectManager.Player, target) && !Utility.InAARange(ObjectManager.Player, mostImportant))) { if (mostImportantsDamage < dmg / 2f) { mostImportant = target; mostImportantsDamage = dmg; continue; } if ((mostImportant.IsMelee && !target.IsMelee) || (!mostImportant.IsMelee && target.IsMelee)) { var targetMultp = GetHealthMultipler(target); var mostImportantsMultp = GetHealthMultipler(mostImportant); if (mostImportantsMultp < targetMultp) { mostImportant = target; mostImportantsDamage = dmg; } } } } } return(mostImportant); } return(null); } } return(null); }
internal static T CreateCommon <T>(string className, int channelId, string name = "Dude", Vector3?pos = null, Quaternion?rot = null, Vector3?scale = null) where T : ActorBase { var actor = Get <T>(channelId); if (actor != null) { return(actor); } var info = Native.ActorInterop.CreateActor(channelId, name, className, pos ?? new Vector3(0, 0, 0), rot ?? Quaternion.Identity, scale ?? new Vector3(1, 1, 1)); if (info.Id == 0) { throw new Exception("Actor creation failed, make sure your IActor implementation is registered with the same name as your managed actor class."); } return(Get <T>(channelId)); }
public static Obj_AI_Hero GetTarget( Obj_AI_Base champion, float range, DamageType type, bool ignoreShieldSpells = true, IEnumerable <Obj_AI_Hero> ignoredChamps = null, Vector3?rangeCheckFrom = null, TargetSelectionConditionDelegate conditions = null) { try { if (ignoredChamps == null) { ignoredChamps = new List <Obj_AI_Hero>(); } var damageType = (Damage.DamageType)Enum.Parse(typeof(Damage.DamageType), type.ToString()); if (_configMenu != null && IsValidTarget( SelectedTarget, _configMenu.Item("ForceFocusSelected").GetValue <bool>() ? float.MaxValue : range, type, ignoreShieldSpells, rangeCheckFrom)) { return(SelectedTarget); } if (_configMenu != null && IsValidTarget( SelectedTarget, _configMenu.Item("ForceFocusSelectedKeys").GetValue <bool>() ? float.MaxValue : range, type, ignoreShieldSpells, rangeCheckFrom)) { if (_configMenu.Item("ForceFocusSelectedK").GetValue <KeyBind>().Active || _configMenu.Item("ForceFocusSelectedK2").GetValue <KeyBind>().Active) { return(SelectedTarget); } } if (_configMenu != null && _configMenu.Item("TargetingMode") != null && Mode == TargetingMode.AutoPriority) { var menuItem = _configMenu.Item("TargetingMode").GetValue <StringList>(); Enum.TryParse(menuItem.SList[menuItem.SelectedIndex], out Mode); } var targets = HeroManager.Enemies.FindAll( hero => ignoredChamps.All(ignored => ignored.NetworkId != hero.NetworkId) && IsValidTarget(hero, range, type, ignoreShieldSpells, rangeCheckFrom) && (conditions == null || conditions(hero))); switch (Mode) { case TargetingMode.LowHP: return(targets.MinOrDefault(hero => hero.Health)); case TargetingMode.MostAD: return(targets.MaxOrDefault(hero => hero.BaseAttackDamage + hero.FlatPhysicalDamageMod)); case TargetingMode.MostAP: return(targets.MaxOrDefault(hero => hero.BaseAbilityDamage + hero.FlatMagicDamageMod)); case TargetingMode.Closest: return (targets.MinOrDefault( hero => (rangeCheckFrom.HasValue ? rangeCheckFrom.Value : champion.ServerPosition).Distance( hero.ServerPosition, true))); case TargetingMode.NearMouse: return(targets.MinOrDefault(hero => hero.Distance(Game.CursorPos, true))); case TargetingMode.AutoPriority: return (targets.MaxOrDefault( hero => champion.CalcDamage(hero, damageType, 100) / (1 + hero.Health) * GetPriority(hero))); case TargetingMode.LessAttack: return (targets.MaxOrDefault( hero => champion.CalcDamage(hero, Damage.DamageType.Physical, 100) / (1 + hero.Health) * GetPriority(hero))); case TargetingMode.LessCast: return (targets.MaxOrDefault( hero => champion.CalcDamage(hero, Damage.DamageType.Magical, 100) / (1 + hero.Health) * GetPriority(hero))); case TargetingMode.MostStack: return (targets.MaxOrDefault( hero => champion.CalcDamage(hero, damageType, 100) / (1 + hero.Health) * GetPriority(hero) + (1 + hero.Buffs.Where(b => StackNames.Contains(b.Name.ToLower())).Sum(t => t.Count)))); } } catch (Exception e) { Console.WriteLine(e); } return(null); }
private void OnMouseDown(SceneView sceneView, Event e) { if (drawMode == DrawMode.None || drawMode == DrawMode.Ambiguous) { startedSubtract = e.shift; } UpdateCSGMode(e); if (selectingHeight) { return; } if (e.clickCount == 2) { // Double click, so finish the polygon if (drawMode == DrawMode.PolygonBase) { if (Is3DView && !startedSubtract) { selectingHeight = true; prismHeight = 0; ignoreNextMouseUp = true; SceneView.RepaintAll(); } else { CreateBrush(hitPoints); ResetTool(); sceneView.Repaint(); } } } else { if (drawMode == DrawMode.None) { PolygonRaycastHit?hit = CalculateHitPolygon(e.mousePosition); if (hit.HasValue) { activePolygon = hit.Value.Polygon; activeBrush = hit.Value.GameObject.GetComponent <PrimitiveBrush>(); } else { activePolygon = null; activeBrush = null; } Vector3?hitPoint = GetHitPoint(e.mousePosition); if (hitPoint.HasValue) { downPoint = hitPoint.Value; hoverPoint = downPoint; } hitPoints.Clear(); if (hitPoint.HasValue) { drawMode = DrawMode.Ambiguous; } } else { Vector3?hitPoint = GetHitPoint(e.mousePosition); if (hitPoint.HasValue) { downPoint = hitPoint.Value; hoverPoint = downPoint; } } } }
protected bool CheckParameters(MonolithState paramState) { if (paramState < currentState) { return(true); } // StarJeb not active vessel if (starJeb != null && FlightGlobals.ActiveVessel != starJeb || candidate != null && FlightGlobals.ActiveVessel != candidate) { stepTime = Time.fixedTime; return(false); } // Create the velocity change handler if (velHdlr == null) { LoggingUtil.LogDebug(this, "Adding VelocityHandler"); velHdlr = MapView.MapCamera.gameObject.AddComponent <VelocityHandler>(); velHdlr.param = this; } switch (currentState) { case MonolithState.STARTED: // Look for an eva if (FlightGlobals.ActiveVessel != null && FlightGlobals.ActiveVessel.vesselType == VesselType.EVA) { candidate = FlightGlobals.ActiveVessel; candidateName = candidate.vesselName; LoggingUtil.LogDebug(this, "Got an eva, starJeb = " + candidate.vesselName); nextState(); return(true); } return(false); case MonolithState.EVA: { Vessel discovery = ContractVesselTracker.Instance.GetAssociatedVessel("Discovery One"); float discoveryDistance = discovery == null ? 10000 : Vector3.Distance(discovery.transform.position, candidate.transform.position); if (distance < 10000 && discoveryDistance > distance && Time.fixedTime - stepTime > 10.0f || distance < MONOLITH_TOO_CLOSE) { // Store Star Jeb's name starJeb = candidate; starJebName = candidateName; PersistentDataStore.Instance.Store <string>("starJebName", starJebName); // Store Star Jeb's friend's name ProtoCrewMember protoStarJeb = candidate.GetVesselCrew().First(); if (discovery != null) { string trait = protoStarJeb.experienceTrait.TypeName == "Scientist" ? "Pilot" : "Scientist"; ProtoCrewMember notStarJeb = discovery.GetVesselCrew().Where(pcm => pcm.experienceTrait.TypeName == trait).FirstOrDefault(); if (notStarJeb != null) { PersistentDataStore.Instance.Store <string>("notStarJebName", notStarJeb.name); } } candidate = null; nextState(); // Set the right image (male vs. female) for the end sequence ConfiguredContract contract = Root as ConfiguredContract; DialogBox dialogBox = contract.Behaviours.Select(b => b as DialogBox).Where(b => b != null).FirstOrDefault(); if (dialogBox != null) { FieldInfo detailsField = typeof(DialogBox).GetFields(BindingFlags.Instance | BindingFlags.NonPublic). Where(fi => fi.FieldType == typeof(List <DialogBox.DialogDetail>)).First(); DialogBox.DialogDetail detail = ((List <DialogBox.DialogDetail>)detailsField.GetValue(dialogBox)).First(); DialogBox.ImageSection starJebImage = detail.sections.First() as DialogBox.ImageSection; starJebImage.imageURL = protoStarJeb.gender == ProtoCrewMember.Gender.Male ? "ContractPacks/AnomalySurveyor/Images/starjeb.dds.noload" : "ContractPacks/AnomalySurveyor/Images/starjeb_female.dds.noload"; } return(true); } } return(false); case MonolithState.FULL_OF_STARS1: { // Backup progress tracking progressTreeBackup = new ConfigNode("PROGRESS_TREE_BACKUP"); ProgressTracking.Instance.OnSave(progressTreeBackup); // Give the first kick away from Jool - this one using regular velocity change CelestialBody jool = FlightGlobals.Bodies.Where(b => b.name == "Jool").First(); // Find closest point on the jool-monolith line, and throw us away from that (so we don't hit either) Vector3 line = monolith.transform.position - jool.transform.position; float t = Vector3.Dot(line, (starJeb.transform.position - jool.transform.position)) / Vector3.Dot(line, line); Vector3 closest = jool.transform.position + line * t; velocity = (starJeb.transform.position - (t > 1.0 ? jool.transform.position : closest)).normalized; velocity += new Vector3(0.0f, 0.1f, 0.0f); velocity *= 15000; LoggingUtil.LogDebug(this, "kick magnitude will be: " + velocity); nextState(); // Camera to target jool FlightCamera.SetTarget(starJeb.transform); FlightCamera.fetch.SetCamCoordsFromPosition((starJeb.transform.position - jool.transform.position).normalized * 25.0f); } return(false); case MonolithState.FULL_OF_STARS2: if (Time.fixedTime - stepTime > 4.0f) { // Give the second kick away from Jool - these using anti-kraken velocity change CelestialBody jool = FlightGlobals.Bodies.Where(b => b.name == "Jool").First(); velocity = (starJeb.transform.position - jool.transform.position).normalized; velocity += new Vector3(0.0f, 0.1f, 0.0f); velocity *= 1500000; LoggingUtil.LogDebug(this, "kick magnitude will be: " + velocity); nextState(); } return(false); case MonolithState.FULL_OF_STARS3: if (Time.fixedTime - stepTime > 3.0f) { // Give the third kick away from Jool CelestialBody jool = FlightGlobals.Bodies.Where(b => b.name == "Jool").First(); velocity = (starJeb.transform.position - jool.transform.position).normalized; velocity *= 20000000; LoggingUtil.LogDebug(this, "kick magnitude will be: " + velocity); nextState(); } return(false); case MonolithState.FULL_OF_STARS4: if (Time.fixedTime - stepTime > 2.0f) { // Give the fourth and final kick away from Jool CelestialBody jool = FlightGlobals.Bodies.Where(b => b.name == "Jool").First(); velocity = (starJeb.transform.position - jool.transform.position).normalized; velocity *= 200000000; LoggingUtil.LogDebug(this, "kick magnitude will be: " + velocity); nextState(); } return(false); case MonolithState.FULL_OF_STARS5: if (Time.fixedTime - stepTime > 2.0f) { // Move along nextState(); } return(false); case MonolithState.FULL_OF_STARS_DRES1: { // Visit Dres CelestialBody dres = FlightGlobals.Bodies.Where(b => b.name == "Dres").First(); // Determine which side the sun is on - makes for a better show CelestialBody sun = FlightGlobals.Bodies.Where(b => b.name == "Sun").First(); Vector3 sunnySide = sun.transform.position - dres.transform.position; sunnySide.x = 0.0f; sunnySide.y = 1; // Move across the top of the planet sunnySide.z = Math.Sign(sunnySide.z); // Set position for starjeb float distance = 4.0f * (float)dres.Radius; starJeb.SetPosition(dres.transform.position + new Vector3(distance, (float)dres.Radius, (float)dres.Radius * sunnySide.z)); velocity = (dres.transform.position - starJeb.transform.position + sunnySide * ((float)dres.Radius)).normalized; velocity *= distance / 3.0f; LoggingUtil.LogDebug(this, "kick magnitude will be: " + velocity); starJeb.SetWorldVelocity(dres.getRFrmVel(starJeb.transform.position)); nextState(); } return(false); case MonolithState.FULL_OF_STARS_DRES2: { // Camera to target Dres - do this on a seperate update to allow KSP to catch up CelestialBody dres = FlightGlobals.Bodies.Where(b => b.name == "Dres").First(); FlightCamera.SetTarget(starJeb.transform); FlightCamera.fetch.SetCamCoordsFromPosition(starJeb.transform.position + (starJeb.transform.position - dres.transform.position).normalized * 10.0f); // Make sure that the camera gets fixed if (Time.fixedTime - stepTime > 0.1f) { nextState(); } } return(false); case MonolithState.FULL_OF_STARS_DRES3: if (Time.fixedTime - stepTime > 5.5f) { // Done with Dres nextState(); } return(false); case MonolithState.FULL_OF_STARS_DUNA1: { // Start between the sun and Duna CelestialBody duna = FlightGlobals.Bodies.Where(b => b.name == "Duna").First(); CelestialBody sun = FlightGlobals.Bodies.Where(b => b.name == "Sun").First(); Vector3 sunnySide = sun.transform.position - duna.transform.position; sunnySide.Normalize(); // Set us up a nice 4 radiuses away... float distance = 4.0f * (float)duna.Radius; starJeb.SetPosition(duna.transform.position + sunnySide * distance); // Go straight at Duna velocity = (duna.transform.position - starJeb.transform.position).normalized; velocity *= distance / 3.0f; LoggingUtil.LogDebug(this, "kick magnitude will be: " + velocity); // Now offset him down so he doesn't actually hit Duna... starJeb.SetPosition(starJeb.transform.position + new Vector3(0.0f, -((float)duna.Radius + 55000), 0.0f)); starJeb.SetWorldVelocity(duna.getRFrmVel(starJeb.transform.position)); nextState(); } return(false); case MonolithState.FULL_OF_STARS_DUNA2: { // Camera to target Duna - do this on a seperate update to allow KSP to catch up CelestialBody duna = FlightGlobals.Bodies.Where(b => b.name == "Duna").First(); FlightCamera.SetTarget(starJeb.transform); FlightCamera.fetch.SetCamCoordsFromPosition(starJeb.transform.position + (starJeb.transform.position - duna.transform.position).normalized * 25.0f); // Make sure that the camera gets fixed if (Time.fixedTime - stepTime > 0.1f) { nextState(); } } return(false); case MonolithState.FULL_OF_STARS_DUNA3: if (Time.fixedTime - stepTime > 5.5f) { // Done with Duna nextState(); } return(false); case MonolithState.FULL_OF_STARS_EELOO1: { // Start perpendicular to the sun and Eeloo CelestialBody eeloo = FlightGlobals.Bodies.Where(b => b.name == "Eeloo").First(); CelestialBody sun = FlightGlobals.Bodies.Where(b => b.name == "Sun").First(); Vector3 perp = eeloo.transform.position - sun.transform.position; float tmp = perp.x; perp.x = -perp.z; perp.z = tmp; perp.Normalize(); // Set us up a nice 4 radiuses away... float distance = 4.0f * (float)eeloo.Radius; starJeb.SetPosition(eeloo.transform.position + perp * distance); // Determine which side the sun is on - makes for a better show Vector3 sunnySide = sun.transform.position - eeloo.transform.position; sunnySide.Normalize(); // Go straight at Eeloo velocity = (eeloo.transform.position - starJeb.transform.position).normalized; velocity *= distance / 3.0f; LoggingUtil.LogDebug(this, "kick magnitude will be: " + velocity); // Now offset him down so he doesn't actually hit Eeloo... starJeb.SetPosition(starJeb.transform.position + sunnySide * ((float)eeloo.Radius * 1.5f)); starJeb.SetWorldVelocity(eeloo.getRFrmVel(starJeb.transform.position)); nextState(); } return(false); case MonolithState.FULL_OF_STARS_EELOO2: { // This time won't target directly towards Eeloo, as the player will have some idea // what is up by now. CelestialBody eeloo = FlightGlobals.Bodies.Where(b => b.name == "Eeloo").First(); CelestialBody sun = FlightGlobals.Bodies.Where(b => b.name == "Sun").First(); Vector3 awayFromSun = sun.transform.position - eeloo.transform.position; awayFromSun.Normalize(); FlightCamera.SetTarget(starJeb.transform); FlightCamera.fetch.SetCamCoordsFromPosition(starJeb.transform.position + awayFromSun * 50.0f); // Make sure that the camera gets fixed if (Time.fixedTime - stepTime > 0.1f) { nextState(); } } return(false); case MonolithState.FULL_OF_STARS_EELOO3: if (Time.fixedTime - stepTime > 5.5f) { velocity = null; // Done with Eeloo nextState(); } return(false); case MonolithState.FULL_OF_STARS_EVE1: { CelestialBody eve = FlightGlobals.Bodies.Where(b => b.name == "Eve").First(); Vector3 targetPosition = Destination.Value; Vector3 normal = eve.GetSurfaceNVector(eveLatitude, eveLongitude); startDistance = 10000000f; Vector3 start = targetPosition + normal * startDistance; starJeb.SetPosition(start); nextState(); } return(false); case MonolithState.FULL_OF_STARS_EVE2: { // Camera straight towards Eve - we're going in! CelestialBody eve = FlightGlobals.Bodies.Where(b => b.name == "Eve").First(); Vector3 awayFromEve = starJeb.transform.position - eve.transform.position; awayFromEve.Normalize(); FlightCamera.SetTarget(starJeb.transform); FlightCamera.fetch.SetCamCoordsFromPosition(starJeb.transform.position + awayFromEve * 15.0f); // Make sure that the camera gets fixed if (Time.fixedTime - stepTime > 0.1f) { nextState(); } } return(false); case MonolithState.FULL_OF_STARS_EVE3: // Wait until we've held the position for a split second if (Time.fixedTime - stepTime >= 9.3f) { nextState(); } return(false); case MonolithState.FULL_OF_STARS_EVE4: // Give the player a bit to get settled, then let the fun begins if (Time.fixedTime - stepTime >= 15.0f) { // Spawn some asteroids CelestialBody eve = FlightGlobals.Bodies.Where(b => b.name == "Eve").First(); ScenarioDiscoverableObjects asteroidSpawner = (ScenarioDiscoverableObjects)HighLogic.CurrentGame.scenarios.Find( s => s.moduleRef is ScenarioDiscoverableObjects).moduleRef; System.Random random = new System.Random(); // Spawn some more asteroids for (int i = 0; i < ASTEROID_COUNT; i++) { asteroidSpawner.SpawnAsteroid(); } nextState(); } return(false); case MonolithState.FULL_OF_STARS_EVE5: // Wait a full second after spawning the asteroids - we're not allowed to pull // them off rails until they've been active a bit if (Time.fixedTime - stepTime > 1.0f) { // Spawn some asteroids CelestialBody eve = FlightGlobals.Bodies.Where(b => b.name == "Eve").First(); System.Random random = new System.Random(); foreach (Vessel asteroid in FlightGlobals.Vessels.Where(v => v.vesselType == VesselType.SpaceObject).Reverse().Take(ASTEROID_COUNT)) { // Set the position double r = random.NextDouble() * 0.02 + 0.002; double theta = random.NextDouble() * 2.0 * Math.PI; double latitude = starJeb.latitude + r * Math.Sin(theta); double longitude = starJeb.longitude + r * Math.Cos(theta); double altitude = starJeb.altitude + 100 + random.NextDouble() * 200; asteroid.SetPosition(eve.GetWorldSurfacePosition(latitude, longitude, altitude)); asteroid.ChangeWorldVelocity(asteroid.GetSrfVelocity()); asteroid.Load(); asteroid.GoOffRails(); } nextState(); } return(false); case MonolithState.FULL_OF_STARS_EVE6: { // Determine if there's an asteroid about to kill us CelestialBody eve = FlightGlobals.Bodies.Where(b => b.name == "Eve").First(); bool killerAsteroid = FlightGlobals.Vessels.Where(v => v.mainBody == eve && v.vesselType == VesselType.SpaceObject && Vector3.Distance(starJeb.transform.position, v.transform.position) < 5.5 * ((int)v.DiscoveryInfo.objectSize + 1)).Any(); if (killerAsteroid || Time.fixedTime - stepTime > 20.0f) { foreach (Vessel asteroid in FlightGlobals.Vessels.Where(v => v.vesselType == VesselType.SpaceObject).Reverse().Take(ASTEROID_COUNT)) { asteroid.Die(); } nextState(); } } return(false); case MonolithState.FULL_OF_STARS_KERBIN1: { CheatOptions.NoCrashDamage = false; // Start between the sun and Kerbin CelestialBody kerbin = FlightGlobals.Bodies.Where(b => b.name == "Kerbin").First(); CelestialBody sun = FlightGlobals.Bodies.Where(b => b.name == "Sun").First(); Vector3 sunnySide = sun.transform.position - kerbin.transform.position; sunnySide.Normalize(); // Set us up a nice 4 radiuses away... float distance = 4.0f * (float)kerbin.Radius; starJeb.SetPosition(kerbin.transform.position + sunnySide * distance); // Orient him properly KerbalEVA keva = starJeb.FindPartModulesImplementing <KerbalEVA>().First(); MethodInfo rotationMethod = typeof(KerbalEVA).GetMethod("correctGroundedRotation", BindingFlags.Instance | BindingFlags.NonPublic); starJeb.packed = true; rotationMethod.Invoke(keva, new object[] { }); starJeb.packed = false; // Hardcode an orbital velocity, because it's late and I'm tired starJeb.SetWorldVelocity(kerbin.getRFrmVel(starJeb.transform.position).normalized * 1085); nextState(); } return(false); case MonolithState.FULL_OF_STARS_KERBIN2: { // Camera to target kerbin - do this on a seperate update to allow KSP to catch up CelestialBody kerbin = FlightGlobals.Bodies.Where(b => b.name == "Kerbin").First(); FlightCamera.SetTarget(starJeb.transform); FlightCamera.fetch.SetCamCoordsFromPosition(starJeb.transform.position + (starJeb.transform.position - kerbin.transform.position).normalized * 10.0f); starJeb.SetRotation(FlightCamera.fetch.transform.rotation * Quaternion.AngleAxis(180.0f, FlightCamera.fetch.transform.up)); // Make sure that the camera gets fixed if (Time.fixedTime - stepTime > 0.1f) { nextState(); } } return(false); case MonolithState.FULL_OF_STARS_KERBIN3: if (Time.fixedTime - stepTime > 2.0f) { // Turn into star jeb CelestialBody kerbin = FlightGlobals.Bodies.Where(b => b.name == "Kerbin").First(); starJeb.vesselName = "The Star Jeb"; Undress(starJeb.gameObject); FlightCamera.fetch.SetCamCoordsFromPosition(starJeb.transform.position + (starJeb.transform.position - kerbin.transform.position).normalized * 1.5f); nextState(); } return(false); case MonolithState.FULL_OF_STARS_KERBIN4: if (Time.fixedTime - stepTime < 15.0f) { CelestialBody kerbin = FlightGlobals.Bodies.Where(b => b.name == "Kerbin").First(); Vector3 camDirection = starJeb.transform.position + (starJeb.transform.position - kerbin.transform.position).normalized; } else { nextState(); monolith.Die(); monolith = null; starJeb.Die(); starJeb = null; Vessel discovery = ContractVesselTracker.Instance.GetAssociatedVessel("Discovery One"); FlightGlobals.ForceSetActiveVessel(discovery); } return(false); case MonolithState.FULL_OF_STARS_FINAL: nextState(); return(true); default: return(false); } }
partial void DrawDebug() { if (Input.GetKeyDown(KeyCode.F1)) { Vector3?eyepos = GetEyePosition(); if (eyepos.HasValue) { CastMeteor(new Vector3(eyepos.Value.x, eyepos.Value.y + 100, eyepos.Value.z)); } } GUI.Label(new Rect(10, 10, 500, 30), $"Player position X = {LocalPlayer.Transform.position.x} Y = {LocalPlayer.Transform.position.y} Z = {LocalPlayer.Transform.position.z}"); if (Physics.Raycast(Camera.main.transform.position + (Vector3.forward * 2), Camera.main.transform.forward, out var raycastInfo, 1000, ~0)) { LayerMask layermasks = GetCollisionMaskOf(raycastInfo.transform.gameObject); GUI.Label(new Rect(10, 30, 500, 30), $"Tag = {raycastInfo.transform.gameObject.tag} Name = {raycastInfo.transform.gameObject.name} LayerMask = {layermasks.value.ToString("X")} Layer = {raycastInfo.transform.gameObject.layer}"); } //Ruler if (rulerObj == null) { rulerObj = new GameObject(); rulerObj.AddComponent <LineRenderer>(); } if (Input.GetKeyDown(KeyCode.F7)) { rulerStart = LocalPlayer.Transform.position; } if (Input.GetKeyDown(KeyCode.F8)) { rulerEnd = LocalPlayer.Transform.position; } if (Input.GetKeyDown(KeyCode.F9)) { rulerStart = Vector3.zero; rulerEnd = Vector3.zero; } if (rulerStart != Vector3.zero && rulerEnd != Vector3.zero) { rulerHue++; Color rulerColor = Color.HSVToRGB((rulerHue % 360) / 360f, 1f, 1f); rulerObj.transform.position = rulerStart; LineRenderer lr = rulerObj.GetComponent <LineRenderer>(); lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply")); lr.SetColors(rulerColor, rulerColor); lr.SetWidth(0.1f, 0.1f); lr.SetPosition(0, rulerStart); lr.SetPosition(1, rulerEnd); Vector3 firstCameraPoint = Camera.main.WorldToScreenPoint(rulerStart); Vector3 lastCameraPoint = Camera.main.WorldToScreenPoint(rulerEnd); if (firstCameraPoint.z > 0f) { firstCameraPoint.y = Screen.height - firstCameraPoint.y; float size = Mathf.Clamp(600 / Vector3.Distance(rulerStart, LocalPlayer.Transform.position), 10, 50); size *= screenScale; Rect r = new Rect(0, 0, 400, size) { center = firstCameraPoint }; GUI.Label(r, $"Client distance = {Vector3.Distance(rulerStart, LocalPlayer.Transform.position)}"); } if (lastCameraPoint.z > 0f) { lastCameraPoint.y = Screen.height - lastCameraPoint.y; float size = Mathf.Clamp(600 / Vector3.Distance(rulerEnd, LocalPlayer.Transform.position), 10, 50); size *= screenScale; Rect r = new Rect(0, 0, 400, size) { center = lastCameraPoint }; GUI.Label(r, $"Client distance = {Vector3.Distance(rulerEnd, LocalPlayer.Transform.position)}\nLineLen = {Vector3.Distance(rulerStart, rulerEnd)}"); } } if (PlayerInventoryMod.EquippedModel != BaseItem.WeaponModelType.None) { GUI.Label(new Rect(600, 300, 500, 30), "Offset"); GUI.Label(new Rect(600, 330, 100, 30), PlayerInventoryMod.customWeapons[PlayerInventoryMod.EquippedModel].offset.x.ToString()); GUI.Label(new Rect(700, 330, 100, 30), PlayerInventoryMod.customWeapons[PlayerInventoryMod.EquippedModel].offset.y.ToString()); GUI.Label(new Rect(800, 330, 100, 30), PlayerInventoryMod.customWeapons[PlayerInventoryMod.EquippedModel].offset.z.ToString()); posX = GUI.TextField(new Rect(600, 360, 100, 30), posX); posY = GUI.TextField(new Rect(700, 360, 100, 30), posY); posZ = GUI.TextField(new Rect(800, 360, 100, 30), posZ); GUI.Label(new Rect(600, 400, 500, 30), "Rotation"); GUI.Label(new Rect(600, 430, 100, 30), PlayerInventoryMod.customWeapons[PlayerInventoryMod.EquippedModel].rotation.x.ToString()); GUI.Label(new Rect(700, 430, 100, 30), PlayerInventoryMod.customWeapons[PlayerInventoryMod.EquippedModel].rotation.y.ToString()); GUI.Label(new Rect(800, 430, 100, 30), PlayerInventoryMod.customWeapons[PlayerInventoryMod.EquippedModel].rotation.z.ToString()); rotX = GUI.TextField(new Rect(600, 460, 100, 30), rotX); rotY = GUI.TextField(new Rect(700, 460, 100, 30), rotY); rotZ = GUI.TextField(new Rect(800, 460, 100, 30), rotZ); if (GUI.Button(new Rect(600, 500, 300, 40), "Apply")) { if (float.TryParse(posX, out float x)) { if (float.TryParse(posY, out float y)) { if (float.TryParse(posZ, out float z)) { Vector3 v = new Vector3(x, y, z); PlayerInventoryMod.customWeapons[PlayerInventoryMod.EquippedModel].obj.transform.localPosition = v; PlayerInventoryMod.customWeapons[PlayerInventoryMod.EquippedModel].offset = v; } } } if (float.TryParse(rotX, out float x1)) { if (float.TryParse(rotY, out float y)) { if (float.TryParse(rotZ, out float z)) { Vector3 v = new Vector3(x1, y, z); PlayerInventoryMod.customWeapons[PlayerInventoryMod.EquippedModel].obj.transform.localRotation = Quaternion.Euler(v); PlayerInventoryMod.customWeapons[PlayerInventoryMod.EquippedModel].rotation = v; } } } } } }
private static Transform DefaultParent(Transform parent, Vector3?worldPos) { return(parent != null ? parent : MatrixManager.GetDefaultParent(worldPos, true)); }
public override void Init(MyObjectBuilder_EntityBase objectBuilder) { base.Init(objectBuilder); var ob = objectBuilder as MyObjectBuilder_FracturedPiece; if (ob.Shapes.Count == 0) { Debug.Fail("Invalid fracture piece! Dont call init without valid OB. Use pool/noinit."); throw new Exception("Fracture piece has no shapes."); //throwing exception, otherwise there is fp with null physics which can mess up somwhere else } foreach (var shape in ob.Shapes) { Render.AddPiece(shape.Name, Matrix.CreateFromQuaternion(shape.Orientation)); } OriginalBlocks.Clear(); foreach (var def in ob.BlockDefinitions) { string model = null; MyPhysicalModelDefinition mdef; if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalModelDefinition>(def, out mdef)) { model = mdef.Model; } MyCubeBlockDefinition blockDef = null; MyDefinitionManager.Static.TryGetDefinition <MyCubeBlockDefinition>(def, out blockDef); if (model == null) { Debug.Fail("Fracture piece Definition not found"); continue; } model = mdef.Model; if (VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes == null) { MyDestructionData.Static.LoadModelDestruction(model, mdef, Vector3.One); } var shape = VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes[0]; var si = new HkdShapeInstanceInfo(shape, null, null); m_children.Add(si); shape.GetChildren(m_children); if (blockDef != null && blockDef.BuildProgressModels != null) { foreach (var progress in blockDef.BuildProgressModels) { model = progress.File; if (VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes == null) { MyDestructionData.Static.LoadModelDestruction(model, blockDef, Vector3.One); } shape = VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes[0]; si = new HkdShapeInstanceInfo(shape, null, null); m_children.Add(si); shape.GetChildren(m_children); } } OriginalBlocks.Add(def); } m_shapes.AddRange(ob.Shapes); Vector3?offset = null; int shapeAtZero = 0; for (int i = 0; i < m_children.Count; i++) { var child = m_children[i]; Func <MyObjectBuilder_FracturedPiece.Shape, bool> x = s => s.Name == child.ShapeName; var result = m_shapes.Where(x); if (result.Count() > 0) { var found = result.First(); var m = Matrix.CreateFromQuaternion(found.Orientation); if (!offset.HasValue && found.Name == m_shapes[0].Name) { offset = child.GetTransform().Translation; shapeAtZero = m_shapeInfos.Count; } m.Translation = child.GetTransform().Translation; var si = new HkdShapeInstanceInfo(child.Shape.Clone(), m); if (found.Fixed) { si.Shape.SetFlagRecursively(HkdBreakableShape.Flags.IS_FIXED); } m_shapeInfos.Add(si); m_shapes.Remove(found); } else { child.GetChildren(m_children); } } if (m_shapeInfos.Count == 0) { List <string> shapesToLoad = new List <string>(); foreach (var obShape in ob.Shapes) { shapesToLoad.Add(obShape.Name); } var shapesStr = shapesToLoad.Aggregate((str1, str2) => str1 + ", " + str2); var blocksStr = OriginalBlocks.Aggregate("", (str, defId) => str + ", " + defId.ToString()); var failMsg = "No relevant shape was found for fractured piece. It was probably reexported and names changed. Shapes: " + shapesStr + ". Original blocks: " + shapesStr; Debug.Fail(failMsg); //HkdShapeInstanceInfo si = new HkdShapeInstanceInfo(new HkdBreakableShape((HkShape)new HkBoxShape(Vector3.One)), Matrix.Identity); //m_shapeInfos.Add(si); throw new Exception(failMsg); } if (offset.HasValue) { for (int i = 0; i < m_shapeInfos.Count; i++) { var m = m_shapeInfos[i].GetTransform(); m.Translation -= offset.Value; m_shapeInfos[i].SetTransform(ref m); } { var m = m_shapeInfos[shapeAtZero].GetTransform(); m.Translation = Vector3.Zero; m_shapeInfos[shapeAtZero].SetTransform(ref m); } } if (m_shapeInfos.Count > 0) { if (m_shapeInfos.Count == 1) { Shape = m_shapeInfos[0].Shape; } else { Shape = new HkdCompoundBreakableShape(null, m_shapeInfos); ((HkdCompoundBreakableShape)Shape).RecalcMassPropsFromChildren(); } Shape.SetStrenght(MyDestructionConstants.STRENGTH); var mp = new HkMassProperties(); Shape.BuildMassProperties(ref mp); Shape.SetChildrenParent(Shape); Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DEBRIS); Physics.CanUpdateAccelerations = true; Physics.InitialSolverDeactivation = HkSolverDeactivation.High; Physics.CreateFromCollisionObject(Shape.GetShape(), Vector3.Zero, PositionComp.WorldMatrix, mp); Physics.BreakableBody = new HkdBreakableBody(Shape, Physics.RigidBody, MyPhysics.SingleWorld.DestructionWorld, (Matrix)PositionComp.WorldMatrix); Physics.BreakableBody.AfterReplaceBody += Physics.FracturedBody_AfterReplaceBody; if (OriginalBlocks.Count > 0) { MyPhysicalModelDefinition def; if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalModelDefinition>(OriginalBlocks[0], out def)) { Physics.MaterialType = def.PhysicalMaterial.Id.SubtypeId; } } var rigidBody = Physics.RigidBody; bool isFixed = MyDestructionHelper.IsFixed(Physics.BreakableBody.BreakableShape); if (isFixed) { rigidBody.UpdateMotionType(HkMotionType.Fixed); rigidBody.LinearVelocity = Vector3.Zero; rigidBody.AngularVelocity = Vector3.Zero; } Physics.Enabled = true; } m_children.Clear(); m_shapeInfos.Clear(); }
// public void Clear() { foundPathForTargetPosition = null; path = null; currentIndex = 0; }
/// <summary> /// Spawns a new actor /// </summary> /// <param name="className"></param> /// <param name="channelId"></param> /// <param name="name"></param> /// <param name="pos"></param> /// <param name="rot"></param> /// <param name="scale"></param> /// <returns></returns> public static ActorBase Create(string className, int channelId, string name = "Dude", Vector3?pos = null, Quaternion?rot = null, Vector3?scale = null) { return(CreateCommon <ActorBase>(className, channelId, name, pos, rot, scale)); }