protected Vector3[] RotateOtherMeshVerts(float angle) { return(VectorUtil.GetRotatedPosition(new Vector3(0.5f, 0.5f, 0.5f), vertsAddDirection, new Vector3(0, angle, 0))); }
// returns cells' WORLD coordinates if the tetramino was moved by offset & rotated according to rotation type public Vector2Int[] GetAbsPoses(Vector2Int offset, Tetramino.RotationType rotation) { Vector2Int[] rotated = RotateArray(Poses, rotationPoint, rotation); return(VectorUtil.Add(rotated, centerPos + offset)); }
internal void Update(GameTime gameTime) { _position = _service.RawClient.CameraPosition.ToXnaVector3(); _forward = _service.RawClient.CameraFront.ToXnaVector3(); _fieldOfView = MathHelper.Clamp((float)_service.RawClient.FieldOfView, 0.01f, (float)Math.PI - 0.01f); // Calculated _view = Matrix.CreateLookAt(_position, _position + _forward, VectorUtil.UpVectorFromCameraForward(_forward)); _playerView = Matrix.CreateLookAt(_position, _service.PlayerCharacter.Position + new Vector3(0, 0, 0.5f), VectorUtil.UpVectorFromCameraForward(_forward)); _projection = Matrix.CreatePerspectiveFieldOfView(this.FieldOfView, GameService.Graphics.AspectRatio, this.NearPlaneRenderDistance, this.FarPlaneRenderDistance); _worldViewProjection = _view * _projection; }
private ActionStatus EndAction() { //OCLogger.Debugging("Ending the " + FullName + " Action."); OCActionArgs args = null; if (_ActionController.Step != null) { args = _ActionController.Step.Arguments; } if (_blockOnFail && _blockOnRunning) { _ActionController.RunningActions.Remove(FullName); } // End animation effects // foreach(OCAnimationEffect afx in _AnimationEffects) // { // afx.Stop(); // } foreach (OCDestroyBlockEffect dbfx in _DestroyBlockEffects) { Vector3i forward = VectorUtil.Vector3ToVector3i(_Source.transform.position + _Source.transform.forward); Vector3i forwardUp = VectorUtil.Vector3ToVector3i(_Source.transform.position + _Source.transform.forward + _Source.transform.up); Vector3i forwardUp2x = VectorUtil.Vector3ToVector3i(_Source.transform.position + _Source.transform.forward + 2 * _Source.transform.up); OCBlockData forwardBlock = _Map.GetBlock(forward); OCBlockData forwardUpBlock = _Map.GetBlock(forwardUp); OCBlockData forwardUp2xBlock = _Map.GetBlock(forwardUp2x); dbfx.DestroyBlock(forward); dbfx.DestroyBlock(forwardUp); dbfx.DestroyBlock(forwardUp2x); args.EndTarget.transform.position = Vector3.zero; args.StartTarget.transform.position = Vector3.zero; // This is just some example code for you Lake, that you can use to give energy to the robot after consuming a battery. if ((forwardBlock.block != null && forwardBlock.block.GetName() == "Battery") || (forwardUpBlock.block != null && forwardUpBlock.block.GetName() == "Battery") || (forwardUp2xBlock.block != null && forwardUp2xBlock.block.GetName() == "Battery")) { UnityEngine.GameObject[] agiArray = UnityEngine.GameObject.FindGameObjectsWithTag("OCAGI"); for (int iAGI = 0; iAGI < agiArray.Length; iAGI++) { UnityEngine.GameObject agiObject = agiArray[iAGI]; //args.EndTarget = agiObject; OCPhysiologicalModel agiPhysModel = agiObject.GetComponent <OCPhysiologicalModel>(); OCPhysiologicalEffect batteryEatEffect = new OCPhysiologicalEffect(OCPhysiologicalEffect.CostLevel.NONE); batteryEatEffect.EnergyIncrease = 0.2f; agiPhysModel.ProcessPhysiologicalEffect(batteryEatEffect); break; } } } //@TODO: Fix this hack... if (Descriptors.Contains("Jump") || Descriptors.Contains("Climb") || Descriptors.Contains("Fall")) { OCCharacterMotor motor = _Source.GetComponent <OCCharacterMotor>(); motor.enabled = true; } if (!Descriptors.Contains("Idle")) { Debug.LogWarning("Ending Action: " + FullName); } // if(args.ActionPlanID != null) // OCConnectorSingleton.Instance.SendActionStatus(args.ActionPlanID, args.SequenceID, args.ActionName, true); return(ActionStatus.SUCCESS); }
//--------------------------------------------------------------------------- #endregion //--------------------------------------------------------------------------- #region Public Member Functions //--------------------------------------------------------------------------- public void SetBlockAndRecompute(OCBlockData block, Vector3i pos) { //MethodInfo info = this.GetType().GetMember("SetBlockAndRecompute")[0] as MethodInfo; // TODO [BLOCKED]: uncomment when aspect stuff is in place? // object[] attributes = info.GetCustomAttributes(typeof(OCLogAspect), true); // OCLogAspect asp = null; // // if(attributes != null) // asp = attributes[0] as OCLogAspect; // // if(asp == null) // Debug.Log("No OCLog Aspect..."); // // asp.OnEntry(null); OCBlockData oldBlock = GetBlock(pos); SetBlock(block, pos); // Convert the global coordinate of the block to the chunk coordinates. Vector3i chunkPos = OCChunk.ToChunkPosition(pos); UpdateChunkLimits(chunkPos); // Convert the global coordinate of the block to the coordinate within the chunk. Vector3i localPos = OCChunk.ToLocalPosition(pos); SetDirty(chunkPos); // If on the lower boundary of a chunk...set the neighbouring chunk to dirty too. if (localPos.x == 0) { SetDirty(chunkPos - Vector3i.right); } if (localPos.y == 0) { SetDirty(chunkPos - Vector3i.up); } if (localPos.z == 0) { SetDirty(chunkPos - Vector3i.forward); } // If on the upper boundary of a chunk...set the neighbouring chunk to dirty too. if (localPos.x == OCChunk.SIZE_X - 1) { SetDirty(chunkPos + Vector3i.right); } if (localPos.y == OCChunk.SIZE_Y - 1) { SetDirty(chunkPos + Vector3i.up); } if (localPos.z == OCChunk.SIZE_Z - 1) { SetDirty(chunkPos + Vector3i.forward); } OpenCog.Map.Lighting.OCSunLightComputer.RecomputeLightAtPosition(this, pos); OpenCog.Map.Lighting.OCLightComputer.RecomputeLightAtPosition(this, pos); UpdateMeshColliderAfterBlockChange(); // TODO [BLOCKED]: uncomment when aspect stuff is in place? // asp.OnExit(null); OpenCog.Embodiment.OCPerceptionCollector perceptionCollector = OpenCog.Embodiment.OCPerceptionCollector.Instance; List <GameObject> batteries = GameObject.FindGameObjectsWithTag("OCBattery").ToList(); GameObject battery = batteries.Where(b => VectorUtil.AreVectorsEqual(b.transform.position, new Vector3((float)pos.x, (float)pos.y, (float)pos.z))).FirstOrDefault(); List <GameObject> hearths = GameObject.FindGameObjectsWithTag("OCHearth").ToList(); GameObject hearth = hearths.Where(h => VectorUtil.AreVectorsEqual(h.transform.position, new Vector3((float)pos.x, (float)pos.y, (float)pos.z))).FirstOrDefault(); if (block.IsEmpty() && !oldBlock.IsEmpty()) { UnityEngine.Debug.Log(OCLogSymbol.RUNNING + "OCMap.SetBlockAndRecompute(): Null block type sent; destroying block."); if (perceptionCollector != null && oldBlock.block.GetName() != "Battery") { perceptionCollector.NotifyBlockRemoved(pos); } // I'm going to take a gamble here...since NotifyBatteryRemoved only does its work when it finds a battery at this location...it should be ok... if (perceptionCollector != null && oldBlock.block.GetName() == "Battery") { perceptionCollector.NotifyBatteryRemoved(pos); } if (battery != default(GameObject) && battery != null) { GameObject.DestroyImmediate(battery); } if (hearth != default(GameObject) && hearth != null) { GameObject.DestroyImmediate(hearth); } } else { UnityEngine.Debug.Log(OCLogSymbol.RUNNING + "OCMap.SetBlockAndRecompute(): Block type sent; creating block."); // Moved notify down...to AFTER the point where it is actually created... } if (block.block != null && block.block.GetName() == "Battery" && (battery == default(GameObject) || battery == null)) { GameObject batteryPrefab = OCMap.Instance.BatteryPrefab; if (batteryPrefab == null) { UnityEngine.Debug.LogWarning(OCLogSymbol.WARN + "OCBuilder.Update(), batteryPrefab == null"); } else { GameObject newBattery = (GameObject)GameObject.Instantiate(batteryPrefab); newBattery.transform.position = pos; newBattery.name = "Battery"; newBattery.transform.parent = OCMap.Instance.BatteriesSceneObject.transform; if (perceptionCollector != null) { perceptionCollector.NotifyBatteryAdded(pos); } } } if (block.block != null && block.block.GetName() == "Hearth" && (hearth == default(GameObject) || hearth == null)) { GameObject hearthPrefab = OCMap.Instance.HearthPrefab; if (hearthPrefab == null) { UnityEngine.Debug.LogWarning(OCLogSymbol.WARN + "OCBuilder::Update, hearthPrefab == null"); } else { GameObject newHearth = (GameObject)GameObject.Instantiate(hearthPrefab); newHearth.transform.position = pos; newHearth.name = "Hearth"; newHearth.transform.parent = OCMap.Instance.HearthsSceneObject.transform; if (perceptionCollector != null) { perceptionCollector.NotifyBlockAdded(pos); } } } }
public void startChangePlayer(bool isPlayerSide) { if (DebugManager.instance.useTagMatchMode == false) { return; } CharacterManager cm = GameManager.me.characterManager; List <Monster> myMonList; List <Monster> enemyMonList; if (isPlayerSide) { if (waitingForPlayerChange) { return; } waitingForPlayerChange = true; GameManager.me.player.setChange(false); myMonList = cm.playerMonster; enemyMonList = cm.monsters; GameManager.me.uiManager.uiPlay.playerChangeControlPanelEffect.gameObject.SetActive(true); StartCoroutine(hidePlayerChangeControllPanelEffect()); // playerChangeDelay.Set(0.5f); } else { if (waitingForPVPChange) { return; } waitingForPVPChange = true; GameManager.me.pvpPlayer.setChange(false); myMonList = cm.monsters; enemyMonList = cm.playerMonster; // pvpChangeDelay.Set(0.5f); } foreach (Monster mon in myMonList) { if (mon.isPlayer == false && mon.isEnabled) { mon.dead(); } } // 교체시 아군 주인공의 위치 기준으로만 넉백이 되는 문제 수정. //if(VersionData.checkCodeVersion(10)) { if (isPlayerSide) { foreach (Monster mon in enemyMonList) { if (mon.isEnabled) { if (Xfloat.lessThan(VectorUtil.Distance(GameManager.me.player.cTransformPosition, mon.cTransformPosition), GameManager.info.setupData.tagKnuckBackValue[0].Get())) { mon.characterEffect.addKnockBack(GameManager.info.setupData.tagKnuckBackValue[1]); if (mon.isPlayer == false) { mon.characterEffect.addStun(GameManager.info.setupData.tagStunTime); } } } } } else { foreach (Monster mon in enemyMonList) { if (mon.isEnabled) { if (Xfloat.lessThan(VectorUtil.Distance(GameManager.me.pvpPlayer.cTransformPosition, mon.cTransformPosition), GameManager.info.setupData.tagKnuckBackValue[0].Get())) { mon.characterEffect.addKnockBack(GameManager.info.setupData.tagKnuckBackValue[1]); if (mon.isPlayer == false) { mon.characterEffect.addStun(GameManager.info.setupData.tagStunTime); } } } } } } /* * else * { * foreach(Monster mon in enemyMonList) * { * if( mon.isEnabled) * { * if( Xfloat.lessThan( VectorUtil.Distance(GameManager.me.player.cTransformPosition, mon.cTransformPosition) , GameManager.info.setupData.tagKnuckBackValue[0].Get() )) * { * mon.characterEffect.addKnockBack(GameManager.info.setupData.tagKnuckBackValue[1]); * } * } * } * } */ }
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { var r0 = new Rect(position.xMin, position.yMin, position.width / 2f, position.height); var r1 = new Rect(r0.xMax, position.yMin, position.width - r0.width, position.height); var propName = property.FindPropertyRelative(PROP_NAME); var propValue = property.FindPropertyRelative(PROP_VALUE); var propRef = property.FindPropertyRelative(PROP_REF); int index = System.Array.IndexOf(_knownPlayerSettingPropNames, propName.stringValue); EditorGUI.BeginChangeCheck(); index = EditorGUI.Popup(r0, GUIContent.none, index, _knownPlayerSettingPropNamesPretty); if (EditorGUI.EndChangeCheck()) { if (index >= 0 && index < _knownPlayerSettingPropNames.Length) { propName.stringValue = _knownPlayerSettingPropNames[index]; } else { propName.stringValue = string.Empty; } propValue.stringValue = string.Empty; propRef.objectReferenceValue = null; } if (index < 0 || index >= _knownPlayerSettings.Length) { return; } var info = _knownPlayerSettings[index]; if (info.PropertyType.IsEnum) { int ei = ConvertUtil.ToInt(propValue.stringValue); propValue.stringValue = ConvertUtil.ToInt(EditorGUI.EnumPopup(r1, ConvertUtil.ToEnumOfType(info.PropertyType, ei))).ToString(); propRef.objectReferenceValue = null; } else { var etp = VariantReference.GetVariantType(info.PropertyType); switch (etp) { case VariantType.Null: propValue.stringValue = string.Empty; propRef.objectReferenceValue = null; break; case VariantType.String: propValue.stringValue = EditorGUI.TextField(r1, propValue.stringValue); propRef.objectReferenceValue = null; break; case VariantType.Boolean: propValue.stringValue = EditorGUI.Toggle(r1, GUIContent.none, ConvertUtil.ToBool(propValue.stringValue)).ToString(); propRef.objectReferenceValue = null; break; case VariantType.Integer: propValue.stringValue = EditorGUI.IntField(r1, GUIContent.none, ConvertUtil.ToInt(propValue.stringValue)).ToString(); propRef.objectReferenceValue = null; break; case VariantType.Float: propValue.stringValue = EditorGUI.FloatField(r1, GUIContent.none, ConvertUtil.ToSingle(propValue.stringValue)).ToString(); propRef.objectReferenceValue = null; break; case VariantType.Double: propValue.stringValue = EditorGUI.DoubleField(r1, GUIContent.none, ConvertUtil.ToDouble(propValue.stringValue)).ToString(); propRef.objectReferenceValue = null; break; case VariantType.Vector2: propValue.stringValue = VectorUtil.Stringify(EditorGUI.Vector2Field(r1, GUIContent.none, ConvertUtil.ToVector2(propValue.stringValue))); propRef.objectReferenceValue = null; break; case VariantType.Vector3: propValue.stringValue = VectorUtil.Stringify(EditorGUI.Vector3Field(r1, GUIContent.none, ConvertUtil.ToVector3(propValue.stringValue))); propRef.objectReferenceValue = null; break; case VariantType.Vector4: propValue.stringValue = VectorUtil.Stringify(EditorGUI.Vector4Field(r1, (string)null, ConvertUtil.ToVector4(propValue.stringValue))); propRef.objectReferenceValue = null; break; case VariantType.Quaternion: propValue.stringValue = QuaternionUtil.Stringify(SPEditorGUI.QuaternionField(r1, GUIContent.none, ConvertUtil.ToQuaternion(propValue.stringValue))); propRef.objectReferenceValue = null; break; case VariantType.Color: propValue.stringValue = ConvertUtil.ToInt(EditorGUI.ColorField(r1, ConvertUtil.ToColor(propValue.stringValue))).ToString(); propRef.objectReferenceValue = null; break; case VariantType.DateTime: //TODO - should never actually occur propValue.stringValue = string.Empty; propRef.objectReferenceValue = null; break; case VariantType.GameObject: case VariantType.Component: case VariantType.Object: propValue.stringValue = string.Empty; propRef.objectReferenceValue = EditorGUI.ObjectField(r1, GUIContent.none, propValue.objectReferenceValue, info.PropertyType, false); break; case VariantType.LayerMask: propValue.stringValue = SPEditorGUI.LayerMaskField(r1, GUIContent.none, ConvertUtil.ToInt(propValue.stringValue)).ToString(); propRef.objectReferenceValue = null; break; case VariantType.Rect: //TODO - should never actually occur propValue.stringValue = string.Empty; propRef.objectReferenceValue = null; break; case VariantType.Numeric: break; } } }
/// return myself correct direction private Vector3 CorrectDirection(Vector3 currentPosition) { Vector3 correctedDir = VectorUtil.RoundXZ(currentPosition); return(correctedDir); }
void DoUpdate() { Vector3 eulers = transform.eulerAngles; switch (operation) { //additive default: case Operation.Additive: if (speed.x != 0f) { var rot = Quaternion.AngleAxis(multiplier.x * speed.x * Time.deltaTime, Vector3.right); if (local) { transform.localRotation *= rot; } else { transform.rotation *= rot; } } if (speed.y != 0f) { var rot = Quaternion.AngleAxis(multiplier.y * speed.y * Time.deltaTime, Vector3.up); if (local) { transform.localRotation *= rot; } else { transform.rotation *= rot; } } if (speed.z != 0f) { var rot = Quaternion.AngleAxis(multiplier.z * speed.z * Time.deltaTime, Vector3.forward); if (local) { transform.localRotation *= rot; } else { transform.rotation *= rot; } } break; //absolute case Operation.Absolute: { var rot = (Vector3.Scale(multiplier, speed)) * Time.timeSinceLevelLoad + offset; if (local) { transform.localEulerAngles = rot; } else { transform.eulerAngles = rot; } } break; //additive sin case Operation.AdditiveSin: if (speed.x != 0f) { var rot = Quaternion.AngleAxis(multiplier.x * Mathf.Sin(speed.x * Mathf.PI * Time.timeSinceLevelLoad), Vector3.right); if (local) { transform.localRotation *= rot; } else { transform.rotation *= rot; } } if (speed.y != 0f) { var rot = Quaternion.AngleAxis(multiplier.y * Mathf.Sin(speed.y * Mathf.PI * Time.timeSinceLevelLoad), Vector3.up); if (local) { transform.localRotation *= rot; } else { transform.rotation *= rot; } } if (speed.z != 0f) { var rot = Quaternion.AngleAxis(multiplier.z * Mathf.Sin(speed.z * Mathf.PI * Time.timeSinceLevelLoad), Vector3.forward); if (local) { transform.localRotation *= rot; } else { transform.rotation *= rot; } } break; //absolute sin case Operation.AbsoluteSin: { var rot = Vector3.Scale(multiplier, VectorUtil.Sin(speed * Mathf.PI * Time.timeSinceLevelLoad)) + offset; if (local) { transform.localEulerAngles = rot; } else { transform.eulerAngles = rot; } } break; } }
protected override bool TestVisibility(VisualAspect aspect) { float aspRad = aspect.Radius; float sqrRadius = _radius * _radius; Vector3 v = aspect.transform.position - this.transform.position; float sqrDist = v.sqrMagnitude; if (sqrDist - (aspRad * aspRad) > sqrRadius) { return(false); } if (this._innerRadius > aspRad && sqrDist < this._innerRadius * this._innerRadius) { return(false); } if (this._horizontalAngle < 360.0f && this._verticalAngle < 360.0f) { Vector3 directionOfAspectInLocalSpace = this.transform.InverseTransformDirection(v); //Quaternion.Inverse(this.transform.rotation) * v; float a; if (aspRad > MathUtil.EPSILON) { float k = 2f * Mathf.Asin(aspRad / (Mathf.Sqrt(sqrDist + (aspRad * aspRad) / 4f))) * Mathf.Rad2Deg; a = VectorUtil.AngleBetween(new Vector2(1f, 0f), new Vector2(directionOfAspectInLocalSpace.z, directionOfAspectInLocalSpace.x)); if (a > (this._horizontalAngle / 2f) - k) { return(false); } a = VectorUtil.AngleBetween(new Vector2(1f, 0f), new Vector2(directionOfAspectInLocalSpace.z, directionOfAspectInLocalSpace.y)); if (a > (this._verticalAngle / 2f) - k) { return(false); } } else { a = VectorUtil.AngleBetween(new Vector2(1f, 0f), new Vector2(directionOfAspectInLocalSpace.z, directionOfAspectInLocalSpace.x)); if (a > this._horizontalAngle / 2f) { return(false); } a = VectorUtil.AngleBetween(new Vector2(1f, 0f), new Vector2(directionOfAspectInLocalSpace.z, directionOfAspectInLocalSpace.y)); if (a > this._verticalAngle / 2f) { return(false); } } } if (this.RequiresLineOfSight) { using (var lst = com.spacepuppy.Collections.TempCollection.GetList <RaycastHit>()) { int cnt = PhysicsUtil.RaycastAll(this.transform.position, v, lst, v.magnitude, this.LineOfSightMask); for (int i = 0; i < cnt; i++) { //we ignore ourself var r = lst[i].collider.FindRoot(); if (r != aspect.entityRoot && r != this.entityRoot) { return(false); } } } } return(true); }
/// return correct coordinate public Vector3 GetCorrectPosition() { Vector3 correctedPos = VectorUtil.RoundXZ(transform.position); return(correctedPos); }
/// <inheritdoc /> public int ComputeClassification(double[] input) { double[] output = ComputeRegression(input); return(VectorUtil.MaxIndex(output)); }
void Update() { if (_isStart && !_isEnding) { if (Time.time >= _timeEnd || (Vector3.Distance(_endPos, tf.position) < 80.0f)) { _targetR = Mathf.Atan2(_endPos.y - tf.position.y, _endPos.x - tf.position.x) * Mathf.Rad2Deg; _dPos.x = Mathf.Cos(_targetR * Mathf.Deg2Rad) * (_pow * Time.deltaTime); _dPos.y = Mathf.Sin(_targetR * Mathf.Deg2Rad) * (_pow * Time.deltaTime); tf.position = Vector3.Lerp(tf.position, tf.position + _dPos, 0.5f); } else { _dPos.x = Mathf.Cos(_r * Mathf.Deg2Rad) * (_pow * Time.deltaTime); _dPos.y = Mathf.Sin(_r * Mathf.Deg2Rad) * (_pow * Time.deltaTime); tf.position += _dPos; _pow += powOffset * Time.deltaTime; _targetR = Mathf.Atan2(_endPos.y - tf.position.y, _endPos.x - tf.position.x) * Mathf.Rad2Deg; while (_targetR > 180f) { _targetR -= 360f; } while (_targetR < -179f) { _targetR += 360f; } _rFromCenter = _r - _targetR; while (_rFromCenter > 180f) { _rFromCenter -= 360f; } while (_rFromCenter < -179f) { _rFromCenter += 360f; } if (_rFromCenter > 1f) { _r -= _rSpeed * Time.deltaTime; } else if (_rFromCenter < -1f) { _r += _rSpeed * Time.deltaTime; } } Vector2 v1 = _endPos; v1.x = _endPos.x; v1.y = _endPos.y; Vector2 v2 = tf.position; v2.x = tf.position.x; v2.y = tf.position.y; if ((VectorUtil.Distance(v1, v2) < 10.0f)) { StopEffect(); } } }
/// decide position of showDropPosBlock /// * @param position - original block position /// * @return expected dropping position private Vector3 ExpectDropPos(Vector3 position) { // set expected x,z // Vector3 correctedBlockPos = VectorUtil.RoundXZ(position); // set expected y // // get offsets for search in array float halfOfWidth = 0.5f; Wall wall = GetBlockPoolController().GetWall(); Vector3 offset = new Vector3(0, 0, 0); offset.x = -wall.GetMinX() - halfOfWidth; offset.z = -wall.GetMinZ() - halfOfWidth; offset.y = -GameObject.Find("BlockPool/Ground").transform.position.y - halfOfWidth; // set y of GetControllingBlockObj() int maxPosY = (int)Math.Round(GetControllingBlockObj().transform.position.y); Vector3 maxHeight = new Vector3(0, maxPosY, 0); var blockCubesPos = new ArrayList(); blockCubesPos.Add( VectorUtil.RoundXZ(GetControllingBlockObj().transform.position) - maxHeight ); foreach (Transform cube in GetControllingBlockObj().transform) { blockCubesPos.Add( VectorUtil.RoundXZ(cube.gameObject.transform.position) - maxHeight ); } // set expected y int height; for (height = maxPosY; height >= 0; height--) { bool isCube = false; foreach (Vector3 cubePos in blockCubesPos) { int cubePosX = (int)Math.Round(cubePos.x + offset.x); int cubePosY = (int)Math.Round(cubePos.y) + height; int cubePosZ = (int)Math.Round(cubePos.z + offset.z); if (cubePosY < 0) { isCube = true; break; } if (GetBlockPoolController().GetSizeY() <= cubePosY) { continue; } if (GetBlockPoolAt(cubePosX, cubePosY, cubePosZ) != null) { isCube = true; break; } } if (isCube) { break; } else { continue; } } height++; correctedBlockPos.y = (float)(height - offset.y); return(correctedBlockPos); }
protected override object GetValueAt(float dt, float t) { return(VectorUtil.Lerp(_start, _target.position, EaseMethods.LinearEaseNone(t, 0f, 1f, this.Duration))); }
protected override bool TestVisibility(VisualAspect aspect) { var sqrRadius = _radius * _radius; var v = aspect.transform.position - this.transform.position; if (v.sqrMagnitude > sqrRadius) { return(false); } if (this._innerRadius > 0f && v.sqrMagnitude < this._innerRadius * this._innerRadius) { return(false); } if (this._horizontalAngle != 360.0f && this._verticalAngle != 360.0f) { Vector3 directionOfAspectInLocalSpace = this.transform.InverseTransformDirection(v); //Quaternion.Inverse(this.transform.rotation) * v; //var lookAtAngles = (VectorUtil.NearZeroVector(directionOfAspectInLocalSpace)) ? Vector3.zero : Quaternion.LookRotation(directionOfAspectInLocalSpace).eulerAngles; //if (Mathf.Abs(lookAtAngles.y * 2.0f) > this._horizontalAngle) // return false; //else if (Mathf.Abs(lookAtAngles.x * 2.0f) > this._verticalAngle) // return false; float a; a = VectorUtil.AngleBetween(new Vector2(1f, 0f), new Vector2(directionOfAspectInLocalSpace.z, directionOfAspectInLocalSpace.x)); if (a > this._horizontalAngle) { return(false); } a = VectorUtil.AngleBetween(new Vector2(1f, 0f), new Vector2(directionOfAspectInLocalSpace.z, directionOfAspectInLocalSpace.y)); if (a > this._verticalAngle) { return(false); } } if (this.RequiresLineOfSight) { //RaycastHit[] hits = Physics.RaycastAll(this.transform.position, v, v.magnitude, this.LineOfSightMask); //foreach(var hit in hits) //{ // //we ignore ourself // var r = hit.collider.FindRoot(); // if (r != aspect.entityRoot && r != this.entityRoot) return false; //} using (var lst = com.spacepuppy.Collections.TempCollection.GetList <RaycastHit>()) { int cnt = PhysicsUtil.RaycastAll(this.transform.position, v, lst, v.magnitude, this.LineOfSightMask); for (int i = 0; i < cnt; i++) { //we ignore ourself var r = lst[i].collider.FindRoot(); if (r != aspect.entityRoot && r != this.entityRoot) { return(false); } } } } return(true); }
public bool RayCast(Vector3 from, Vector3 to, RayCastCallback callback = null) { Vector3 r = to - from; r.Normalize(); float maxFraction = 1.0f; // v is perpendicular to the segment. Vector3 v = VectorUtil.FindOrthogonal(r).normalized; Vector3 absV = VectorUtil.Abs(v); // build a bounding box for the segment. Aabb rayBounds = Aabb.Empty; rayBounds.Include(from); rayBounds.Include(to); m_stack.Clear(); m_stack.Push(m_root); bool hitAnyBounds = false; while (m_stack.Count > 0) { int index = m_stack.Pop(); if (index == Null) { continue; } if (!Aabb.Intersects(m_nodes[index].Bounds, rayBounds)) { continue; } // Separating axis for segment (Gino, p80). // |dot(v, a - c)| > dot(|v|, h) Vector3 c = m_nodes[index].Bounds.Center; Vector3 h = m_nodes[index].Bounds.HalfExtents; float separation = Mathf.Abs(Vector3.Dot(v, from - c)) - Vector3.Dot(absV, h); if (separation > 0.0f) { continue; } if (m_nodes[index].IsLeaf) { Aabb tightBounds = m_nodes[index].Bounds; tightBounds.Expand(-FatBoundsRadius); float t = tightBounds.RayCast(from, to, maxFraction); if (t < 0.0f) { continue; } hitAnyBounds = true; float newMaxFraction = callback != null ? callback(from, to, m_nodes[index].UserData) : maxFraction; if (newMaxFraction >= 0.0f) { // Update segment bounding box. maxFraction = newMaxFraction; Vector3 newTo = from + maxFraction * (to - from); rayBounds.Min = VectorUtil.Min(from, newTo); rayBounds.Max = VectorUtil.Max(from, newTo); } } else { m_stack.Push(m_nodes[index].ChildA); m_stack.Push(m_nodes[index].ChildB); } } return(hitAnyBounds); }
private void shoot() { _burstTimer = 0.0f; _shotsFired++; GameObject bulletObj = Instantiate(_bulletPrefab); Bullet bullet = bulletObj.GetComponent <Bullet>(); Vector3 target = PlayerManager.Instance.PlayerPosition + _aimLookahead * Vector3.forward + VectorUtil.RandVec3(_aimJitter); Vector3 delta = target - transform.position; bullet.Init(transform.position, delta); }
public void cutSceneUpdate() { if (cutScenePositionTween == CutSceneTweenType.Position) { if (cutScenePositionTweenType == 1) { setPositionCtransform(cTransform.position + tf.forward * csTweenSpeed * CutSceneManager.cutSceneDeltaTime); if (VectorUtil.Distance3D(csStartPos, cTransformPosition) >= csTargetDistance) { onCompleteCutScenePositionTween(); } } else if (cutScenePositionTweenType == 2) { if (csObjectMove2Tweener.update(CutSceneManager.cutSceneDeltaTime, this) == false) { onCompleteCutScenePositionTween(); } } } else if (cutScenePositionTween == CutSceneTweenType.PositionWithNoRotation) { if (cutScenePositionTweenType == 1) { setPositionCtransform(Vector3.MoveTowards(cTransform.position, csTargetPos, csTweenSpeed * CutSceneManager.cutSceneDeltaTime)); if (VectorUtil.Distance3D(csStartPos, cTransformPosition) >= csTargetDistance) { onCompleteCutScenePositionTween(); } } else if (cutScenePositionTweenType == 2) { if (csObjectMove2Tweener.update(CutSceneManager.cutSceneDeltaTime, this) == false) { onCompleteCutScenePositionTween(); } } } else if (isCutSceneUpdownMotion && Time.timeScale > 0) { _csUpDownDelta += CutSceneManager.cutSceneDeltaTime * csUpDownSpeed; _v = cTransform.position; _v.y = csUpDownCenter + Mathf.Sin(_csUpDownDelta) * csUpDownRange; setPositionCtransform(_v); } if (isCutSceneRotationTween) { _csProgressDeltaTime += CutSceneManager.cutSceneDeltaTime; if (_csProgressDeltaTime >= csTweenTime) { tf.rotation = _csTargetRotation; isCutSceneRotationTween = false; } else { tf.rotation = Quaternion.Slerp(_csStartRotation, _csTargetRotation, _csProgressDeltaTime / csTweenTime); } } if (csObjectColorTweener.isEnabled) { csObjectColorTweener.update(CutSceneManager.cutSceneDeltaTime, this); } if (csScaleTweener.isEnabled) { csScaleTweener.update(CutSceneManager.cutSceneDeltaTime, cTransform); } // 데미지 모션용 ================ // updateCutSceneDamageMotion(); }
/// <summary> /// Stops the block from moving horizontally. /// </summary> private void FixedUpdate() { body.velocity = VectorUtil.SetXZ(body.velocity, 0); }
public static bool IsNaN(Trans t) { return(VectorUtil.IsNaN(t.Position) || VectorUtil.IsNaN(t.Scale) || QuaternionUtil.IsNaN(t.Rotation)); }
void move(Monster target) { if (GameManager.me.stageManager.playTime - _infoShowTime > 0.5f) { _m = (int)(VectorUtil.Distance(GameManager.me.player.cTransformPosition.x, mon.cTransformPosition.x) * 0.01f); if (_m != _infoValue) { GameManager.me.uiManager.uiPlay.lbChaser.text = "-" + _m + "m"; _infoValue = _m; _infoShowTime = GameManager.me.stageManager.playTime; } } _target = target; mon.attackPosition = Util.getPositionByAngleAndDistanceXZ(0, mon.stat.atkRange + _target.damageRange + mon.damageRange); // hitrange //mon.action.delay = 0.3f; _v = _target.cTransformPosition + mon.attackPosition; if (VectorUtil.DistanceXZ(_target.cTransformPosition, mon.cTransformPosition) <= mon.stat.atkRange + _target.damageRange + mon.damageRange) // hitrange { _v = _target.cTransformPosition - mon.cTransformPosition; _q = Util.getLookRotationQuaternion(_v); // 자리를 다 잡았으면 공격... mon.tf.rotation = Util.getFixedQuaternionSlerp(mon.tf.rotation, _q, CharacterAction.rotationSpeed * GameManager.globalDeltaTime); if ((mon.action.delay > 0 || Xfloat.greaterThan(Quaternion.Angle(_q, mon.tf.rotation), 5)) || _target.isEnabled == false) { mon.state = Monster.NORMAL; mon.action.delay -= GameManager.globalDeltaTime; } else { mon.action.state = CharacterAction.STATE_ACTION; } } else if (mon.cTransformPosition.x + mon.attackPosition.x >= _target.cTransformPosition.x && VectorUtil.Distance(_v.z, mon.cTransformPosition.z) < 5) { //Debug.Log("1"); _v = _target.cTransformPosition - mon.cTransformPosition; _q = Util.getLookRotationQuaternion(_v); // 자리를 다 잡았으면 공격... mon.tf.rotation = Util.getFixedQuaternionSlerp(mon.tf.rotation, _q, CharacterAction.rotationSpeed * GameManager.globalDeltaTime); if ((mon.action.delay > 0 || Xfloat.greaterThan(Quaternion.Angle(_q, mon.tf.rotation), 5)) || _target.isEnabled == false) { mon.state = Monster.NORMAL; mon.action.delay -= GameManager.globalDeltaTime; } else { mon.action.state = CharacterAction.STATE_ACTION; } } else { _v = _target.cTransformPosition + mon.attackPosition; _q = Util.getLookRotationQuaternion(_v - mon.cTransformPosition); mon.tf.rotation = Util.getFixedQuaternionSlerp(mon.tf.rotation, _q, CharacterAction.rotationSpeed * GameManager.globalDeltaTime); _v = mon.cTransformPosition + mon.tf.forward * mon.stat.speed * GameManager.globalDeltaTime; _v.y = 0; mon.setPlayAniRightNow(Monster.WALK); mon.animation[Monster.WALK].speed = 0.3f; mon.setPosition(_v); } }
protected override bool TestVisibility(VisualAspect aspect) { //if not in cylinder, can not see it var halfHeight = _height / 2.0f; var rod = this.Rod; var center = this.GetCenterInWorldSpace(); var otherPos = aspect.transform.position; float aspRad = aspect.Radius; if (aspRad > MathUtil.EPSILON) { if (!Cylinder.ContainsSphere(center - (rod * halfHeight), center + (rod * halfHeight), _radius, _innerRadius, otherPos, aspRad)) { return(false); } if (this._angle < 360.0f) { var v = VectorUtil.SetLengthOnAxis(otherPos - center, rod, 0f); var a = Vector3.Angle(this.transform.forward, v); float k = 2f * Mathf.Asin(aspRad / (Mathf.Sqrt(v.sqrMagnitude + (aspRad * aspRad) / 4f))) * Mathf.Rad2Deg; if (a > (_angle / 2.0f) - k) { return(false); } } } else { if (!Cylinder.ContainsPoint(center - (rod * halfHeight), center + (rod * halfHeight), _radius, _innerRadius, otherPos)) { return(false); } if (this._angle < 360.0f) { var v = VectorUtil.SetLengthOnAxis(otherPos - center, rod, 0f); var a = Vector3.Angle(this.transform.forward, v); if (a > this._angle / 2.0f) { return(false); } } } if (this.LineOfSightMask.value != 0) { var v = otherPos - center; using (var lst = com.spacepuppy.Collections.TempCollection.GetList <RaycastHit>()) { int cnt = PhysicsUtil.RaycastAll(this.transform.position, v, lst, v.magnitude, this.LineOfSightMask); for (int i = 0; i < cnt; i++) { //we ignore ourself var r = lst[i].collider.FindRoot(); if (r != aspect.entityRoot && r != this.entityRoot) { return(false); } } } } return(true); }
//--------------------------------------------------------------------------- #endregion //--------------------------------------------------------------------------- #region Public Member Functions //--------------------------------------------------------------------------- public void CreateBlock(Vector3i?point) { if (point.HasValue) { OCMap map = OCMap.Instance; //(OCMap)GameObject.FindSceneObjectsOfType(typeof(OCMap)).FirstOrDefault(); OCBlock block = map.GetBlockSet().GetBlock(_BlockType); OCGoalController[] goalControllers = (OCGoalController[])GameObject.FindObjectsOfType(typeof(OCGoalController)); foreach (OCGoalController goalController in goalControllers) { if (goalController.GoalBlockType == block) { goalController.FindGoalBlockPositionInChunks(map.GetChunks()); } } //block.SetDirection(GetDirection(-gameObject.transform.forward)); OCBlockData blockData = OCBlockData.CreateInstance <OCBlockData>().Init(block, VectorUtil.Vector3ToVector3i(point.Value)); map.SetBlockAndRecompute(blockData, point.Value); } }
public bool IsPathOpen(UnityEngine.Transform characterTransform, float characterHeight, PathDirection intendedDirection, Vector3i targetPosition) { bool bPathIsOpen = false; Vector3i vCharForward = VectorUtil.Vector3ToVector3i(characterTransform.forward); Vector3i vCharLeft = VectorUtil.Vector3ToVector3i(-characterTransform.right); Vector3i vCharRight = VectorUtil.Vector3ToVector3i(characterTransform.right); //Debug.Log ("vFeetPosition = [" + vFeetPosition.x + ", " + vFeetPosition.y + ", " + vFeetPosition.z + "]"); //Debug.Log ("vFeetForwardPosition = [" + vFeetForwardPosition.x + ", " + vFeetForwardPosition.y + ", " + vFeetForwardPosition.z + "]"); UnityEngine.Vector3 vFeet = new UnityEngine.Vector3(characterTransform.position.x, characterTransform.position.y, characterTransform.position.z); vFeet.y -= (characterHeight / 2); UnityEngine.Vector3 vFeetForward = characterTransform.forward + vFeet; Vector3i viStandingOn = VectorUtil.Vector3ToVector3i(vFeet); //Debug.Log ("Standing on world block: [" + viStandingOn.x + ", " + viStandingOn.y + ", " + viStandingOn.z + "]"); Vector3i viStandingOnForward = VectorUtil.Vector3ToVector3i(vFeetForward); //Debug.Log ("Forward of standing on world block: [" + viStandingOnForward.x + ", " + viStandingOnForward.y + ", " + viStandingOnForward.z + "]"); Vector3i viLowerBody = new Vector3i(viStandingOn.x, viStandingOn.y, viStandingOn.z); viLowerBody += new Vector3i(0, 1, 0); //Debug.Log ("Lower body inhabits world block: [" + viLowerBody.x + ", " + viLowerBody.y + ", " + viLowerBody.z + "]"); Vector3i viUpperBody = new Vector3i(viLowerBody.x, viLowerBody.y, viLowerBody.z); viUpperBody += new Vector3i(0, 1, 0); //Debug.Log ("Upper body inhabits world block: [" + viUpperBody.x + ", " + viUpperBody.y + ", " + viUpperBody.z + "]"); // Prepare some block vectors to use later. Vector3i viOneAboveHead = viUpperBody + Vector3i.up; // The block direct above the upper body Vector3i viTwoAboveHead = viOneAboveHead + Vector3i.up; // The block two above the upper body Vector3i viForwardOneUnder = viStandingOnForward; // The block in front, one down Vector3i viForwardKneeHigh = viStandingOnForward + Vector3i.up; // The block in front of the lower body Vector3i viForwardChestHigh = viForwardKneeHigh + Vector3i.up; // The block in front of the upper body Vector3i viForwardOneAboveHead = viForwardChestHigh + Vector3i.up; // The block one above the block in front of the upper body Vector3i viForwardTwoAboveHead = viForwardOneAboveHead + Vector3i.up; // The block two above the block in front of the upper body Vector3i viTwoForwardKneeHigh = viForwardKneeHigh + vCharForward; // The block two steps ahead, in front of the lower body Vector3i viTwoForwardChestHigh = viForwardChestHigh + vCharForward; // The block two steps ahead, in front of the upper body //Vector3i viTwoForwardOneAboveHead = viTwoForwardChestHigh + Vector3i.up; // The block one above the block in front of the upper body //Vector3i viTwoForwardTwoAboveHead = viTwoForwardOneAboveHead + Vector3i.up; // The block two above the block in front of the upper body Vector3i viThreeForwardKneeHigh = viTwoForwardKneeHigh + vCharForward; // The block three steps ahead, in front of the lower body Vector3i viThreeForwardChestHigh = viTwoForwardChestHigh + vCharForward; // The block three steps ahead, in front of the upper body //Vector3i viThreeForwardOneAboveHead = viThreeForwardChestHigh + Vector3i.up; // The block one above the block in front of the upper body //Vector3i viThreeForwardTwoAboveHead = viThreeForwardOneAboveHead + Vector3i.up; // The block two above the block in front of the upper body Vector3i viTwoForwardOneUnder = viStandingOnForward + vCharForward; // The block two steps ahead, one down Vector3i viThreeForwardOneUnder = viTwoForwardOneUnder + vCharForward; // The block three steps ahead, one down //Debug.Log ("Forward knee high: [" + viForwardKneeHigh.x + ", " + viForwardKneeHigh.y + ", " + viForwardKneeHigh.z + "]"); //Debug.Log ("Forward chest high: [" + viForwardChestHigh.x + ", " + viForwardChestHigh.y + ", " + viForwardChestHigh.z + "]"); //Debug.Log ("Forward one under: [" + viForwardOneUnder.x + ", " + viForwardOneUnder.y + ", " + viForwardOneUnder.z + "]"); //Debug.Log ("Forward lower block is: [" + viForwardKneeHigh.x + ", " + viForwardKneeHigh.y + ", " + viForwardKneeHigh.z + "]"); //Debug.Log ("Forward upper block is: [" + viForwardChestHigh.x + ", " + viForwardChestHigh.y + ", " + viForwardChestHigh.z + "]"); switch (intendedDirection) { case PathDirection.ForwardWalk: // Requires two clear blocks in front if (GetBlock(viForwardKneeHigh).IsEmpty() && GetBlock(viForwardChestHigh).IsEmpty()) { // And one block under in front if (GetBlock(viForwardOneUnder).IsSolid()) { bPathIsOpen = true; } } break; case PathDirection.ForwardLeftWalk: // Requires two clear blocks in front if (GetBlock(viForwardKneeHigh + vCharLeft).IsEmpty() && GetBlock(viForwardChestHigh + vCharLeft).IsEmpty()) { // And one block under in front if (GetBlock(viForwardOneUnder + vCharLeft).IsSolid()) { bPathIsOpen = true; } } break; case PathDirection.ForwardRightWalk: // Requires two clear blocks in front if (GetBlock(viForwardKneeHigh + vCharRight).IsEmpty() && GetBlock(viForwardChestHigh + vCharRight).IsEmpty()) { // And one block under in front if (GetBlock(viForwardOneUnder + vCharRight).IsSolid()) { bPathIsOpen = true; } } break; case PathDirection.ForwardRun: // Requires two clear blocks for the next 3 forwards if (GetBlock(viForwardKneeHigh).IsEmpty() && GetBlock(viForwardChestHigh).IsEmpty()) { if (GetBlock(viTwoForwardKneeHigh).IsEmpty() && GetBlock(viTwoForwardChestHigh).IsEmpty()) { if (GetBlock(viThreeForwardKneeHigh).IsEmpty() && GetBlock(viThreeForwardChestHigh).IsEmpty()) { if (GetBlock(viForwardOneUnder).IsSolid() && GetBlock(viTwoForwardOneUnder).IsSolid() && GetBlock(viThreeForwardOneUnder).IsSolid()) { bPathIsOpen = true; } } } } break; case PathDirection.ForwardClimb: // Requires a solid block lower front if (GetBlock(viForwardKneeHigh).IsSolid()) { // And two empty blocks above that if (GetBlock(viForwardChestHigh).IsEmpty() && GetBlock(viForwardOneAboveHead).IsEmpty()) { bPathIsOpen = true; } } break; case PathDirection.ForwardDrop: // Requires 3 empty block in front, chest high, knee high and 1 underground if (GetBlock(viForwardKneeHigh).IsEmpty() && GetBlock(viForwardChestHigh).IsEmpty() && GetBlock(viForwardOneUnder).IsEmpty()) { bPathIsOpen = true; } break; case PathDirection.UpwardJump: // Requires two empty blocks above if (GetBlock(viOneAboveHead).IsEmpty() && GetBlock(viTwoAboveHead).IsEmpty()) { bPathIsOpen = true; } break; case PathDirection.ForwardJump: // Requires two empty blocks above, and one empty blocks in front of the higher of those if (GetBlock(viOneAboveHead).IsEmpty() && GetBlock(viTwoAboveHead).IsEmpty() && GetBlock(viForwardTwoAboveHead).IsEmpty()) { bPathIsOpen = true; } break; case PathDirection.ForwardBlockEmpty: if (GetBlock(viForwardChestHigh).IsEmpty() && GetBlock(viForwardKneeHigh).IsEmpty() && GetBlock(viForwardOneAboveHead).IsEmpty()) { bPathIsOpen = true; } break; case PathDirection.ForwardBlockSolid: if (GetBlock(viForwardChestHigh).IsSolid() || GetBlock(viForwardKneeHigh).IsSolid() || GetBlock(viForwardOneAboveHead).IsSolid()) { bPathIsOpen = true; } break; case PathDirection.AdjacentBlockEmpty: if (GetBlock(viForwardKneeHigh).IsEmpty()) { bPathIsOpen = true; } break; case PathDirection.AdjacentBlockSolid: if (GetBlock(viForwardKneeHigh).IsSolid()) { bPathIsOpen = true; } break; default: Debug.LogError(OCLogSymbol.ERROR + "Undefined PathDirection in IsPathOpen(basePosition, intendedDirection)"); break; } //Debug.Log ("Test for PathDirection=" + intendedDirection.ToString () + " yields " + bPathIsOpen); return(bPathIsOpen); }
public void UpdateAI() { _ActionPlanList = _ActionPlanQueue.ToList(); if (_step == null && _ActionPlanQueue.Count != 0) { _step = _ActionPlanQueue.First(); _ActionPlanQueue.RemoveFirst(); Debug.LogWarning("In OCActionController.UpdateAI, starting action step: " + _step.Arguments.ActionName + ", retry: " + _step.Retry); } else if (_step == null && _ActionPlanQueue.Count == 0) { _PlanSucceeded = true; OCActionPlanStep step = OCScriptableObject.CreateInstance <OCActionPlanStep>(); step.Behaviour = _TreeTypeDictionary[_TreeType]; step.Arguments = new OCAction.OCActionArgs(_defaultSource, _defaultStartTarget, _defaultEndTarget); KeyValuePair <string, TreeType> keyValuePair = _ActionNameDictionary.First(s => s.Value == _TreeType); step.Arguments.ActionName = keyValuePair.Key; _step = step; } BehaveResult result = _step.Behaviour.Tick(); // if((_step.Behaviour.Name == _TreeTypeDictionary[TreeType.Character_IdleShow].Name) && result == BehaveResult.Success) // { // //iTween itween = _step.Arguments.Source.GetComponent<iTween>(); // iTween.Stop(_step.Arguments.Source); // } if (result != BehaveResult.Running) { OCAction.OCActionArgs args = _step.Arguments; // if((_step.Behaviour.Name != _TreeTypeDictionary[_TreeType].Name) // || ((_step.Behaviour.Name == _TreeTypeDictionary[_TreeType].Name) // && (GameObject.Find("EndPointStub").transform.position != Vector3.zero))) { // if we have a goal... if (_step.Arguments.EndTarget != null) { if (_step.Arguments.EndTarget.transform.position != Vector3.zero) { _PlanSucceeded &= result == BehaveResult.Success; } Vector3 startPosition = _step.Arguments.StartTarget.transform.position; Vector3 endPosition = _step.Arguments.EndTarget.transform.position; Vector3 sourcePosition = _step.Arguments.Source.transform.position; sourcePosition.y = sourcePosition.y - 0.5f; Vector3 startToEnd = endPosition - startPosition; Vector3 sourceToEnd = endPosition - sourcePosition; float startToEndManDist = Math.Abs(endPosition.x - startPosition.x) + Math.Abs(endPosition.y - startPosition.y) + Math.Abs(endPosition.z - startPosition.z); float sourceToEndManDist = Math.Abs(endPosition.x - sourcePosition.x) + Math.Abs(endPosition.y - sourcePosition.y) + Math.Abs(endPosition.z - sourcePosition.z); if (_step.Behaviour.Name == "Character.Move" || _step.Arguments.ActionName == "walk" || _step.Arguments.ActionName == "jump_toward") { // don't use euclideon distance //_PlanSucceeded |= sourceToEnd.sqrMagnitude < startToEnd.sqrMagnitude; // use manhattan distance //_PlanSucceeded = sourceToEndManDist <= startToEndManDist; if (VectorUtil.AreVectorsEqual(sourcePosition, endPosition)) { _PlanSucceeded = true; } else { _PlanSucceeded = false; } } if (_step.Behaviour.Name == "Character.Destroy" || _step.Arguments.ActionName == "eat") { _PlanSucceeded = (endPosition == Vector3.zero || _step.Arguments.EndTarget == null); } if (_step.Arguments.ActionName == "grab") { _PlanSucceeded = OCAction.IsEndTargetCloseForward(null, _step.Arguments); } // if(_step.Arguments.ActionName == "grab") // { // _PlanSucceeded = endPosition != startPosition && endPosition != null; // } if (_step.Arguments.ActionPlanID != null && (_PlanSucceeded || _step.Retry > OCActionPlanStep.MaxRetries)) { OCConnectorSingleton.Instance.SendActionStatus(args.ActionPlanID, args.SequenceID, args.ActionName, _PlanSucceeded); if (_step.Behaviour.Name != "Character.IdleShow" && !_step.Behaviour.Name.Contains("Behaviour")) { Debug.LogWarning("In OCActionController.UpdateAI, Result: " + (_PlanSucceeded ? "Success" : "Failure") + " for Action: " + (_step.Arguments.ActionName == null ? _step.Behaviour.Name : (_step.Arguments.ActionName + " & Sequence: " + _step.Arguments.SequenceID))); } } else if (_step.Arguments.ActionPlanID == null && (_PlanSucceeded || _step.Retry > OCActionPlanStep.MaxRetries) && OCConnectorSingleton.Instance.IsEstablished) { OCConnectorSingleton.Instance.HandleOtherAgentActionResult(_step, _PlanSucceeded); } } // if(!_PlanSucceeded) // Debug.LogWarning(" -- Step Failed: " + (_step.Arguments.ActionName == null ? _step.Behaviour.Name : _step.Arguments.ActionName)); _step.Behaviour.Reset(); // if we failed, retry last step if (_PlanSucceeded == false && OCActionPlanStep.MaxRetries > _step.Retry) { _ActionPlanQueue.AddFirst(_step); _step.Retry += 1; } else if (_PlanSucceeded == false && OCActionPlanStep.MaxRetries <= _step.Retry) { _ActionPlanQueue.Clear(); _step = null; } else if (_step.Arguments.EndTarget) { OCFadeOutGameObject fadeOut = _step.Arguments.EndTarget.GetComponent <OCFadeOutGameObject>(); if (fadeOut != null) { fadeOut.enabled = true; } } if (_ActionPlanQueue.Count == 0) { if (_LastPlanID != null) { // if(result == BehaveResult.Failure) // OCConnectorSingleton.Instance.SendActionStatus(args.ActionPlanID, args.SequenceID, args.ActionName, true); OCConnectorSingleton.Instance.SendActionPlanStatus(_LastPlanID, _PlanSucceeded); if (_step != null && _step.Arguments.EndTarget != null) { OCFadeOutGameObject fadeOut = _step.Arguments.EndTarget.GetComponent <OCFadeOutGameObject>(); if (fadeOut != null) { fadeOut.enabled = true; } } _LastPlanID = null; } _step = null; } else if (_LastPlanID != null) { _step = _ActionPlanQueue.First(); _ActionPlanQueue.RemoveFirst(); Debug.LogWarning("In OCActionController.UpdateAI, starting action step: " + _step.Arguments.ActionName + ", retry: " + _step.Retry); if (_LastPlanID != _step.Arguments.ActionPlanID) { Debug.LogError("We've changed plans without reporting back to OpenCog!"); } } else { _LastPlanID = _step.Arguments.ActionPlanID; _step = _ActionPlanQueue.First(); _ActionPlanQueue.RemoveFirst(); Debug.LogWarning("In OCActionController.UpdateAI, starting action step: " + _step.Arguments.ActionName + ", retry: " + _step.Retry); } } } }
public static int OverlapCapsule(Vector3 point1, Vector3 point2, float radius, ICollection <Collider> results, int layerMask = Physics.AllLayers, QueryTriggerInteraction query = QueryTriggerInteraction.UseGlobal) { if (results == null) { throw new System.ArgumentNullException("results"); } //note, HashSets are inherently unique collections... so no need to check if contains during second and third overlaps using (var tmpSet = TempCollection.GetSet <Collider>()) { if (VectorUtil.FuzzyEquals(point1, point2)) { var nonAllocArr = NonAllocColliderBuffer; int cnt = Physics.OverlapSphereNonAlloc(point1, radius, nonAllocArr, layerMask, query); for (int i = 0; i < cnt; i++) { tmpSet.Add(nonAllocArr[i]); nonAllocArr[i] = null; } } else { var nonAllocCollArr = NonAllocColliderBuffer; var nonAllocRayArr = NonAllocRaycastBuffer; int cnt; cnt = Physics.OverlapSphereNonAlloc(point1, radius, nonAllocCollArr, layerMask, query); for (int i = 0; i < cnt; i++) { tmpSet.Add(nonAllocCollArr[i]); nonAllocCollArr[i] = null; } cnt = Physics.OverlapSphereNonAlloc(point2, radius, nonAllocCollArr, layerMask, query); for (int i = 0; i < cnt; i++) { tmpSet.Add(nonAllocCollArr[i]); nonAllocCollArr[i] = null; } var dir = point2 - point1; var dist = dir.magnitude; cnt = Physics.SphereCastNonAlloc(point1, radius, dir.normalized, nonAllocRayArr, dist, layerMask, query); for (int i = 0; i < cnt; i++) { tmpSet.Add(nonAllocRayArr[i].collider); nonAllocRayArr[i] = default(RaycastHit); } } //done, now fill collection if (results is Collider[]) { var arr = results as Collider[]; int cnt = Mathf.Min(arr.Length, tmpSet.Count); int i = -1; var e = tmpSet.GetEnumerator(); while (e.MoveNext() && ++i < cnt) { arr[i] = e.Current; } return(cnt); } else { if (results is List <Collider> ) { var lst = results as List <Collider>; var num = tmpSet.Count + lst.Count; if (lst.Capacity < num) { lst.Capacity = num; } } var e = tmpSet.GetEnumerator(); while (e.MoveNext()) { results.Add(e.Current); } return(tmpSet.Count); } } }
void updateBullets(List <Bullet> bulletList, List <Monster> targetMonsterList) { int j = 0; bool isSkip = false; bool isHit = false; IFloat _tempF; for (int i = bulletList.Count - 1; i >= 0; --i) { if (bulletList[i].isDeleteObject) { setBullet(bulletList[i]); bulletList.RemoveAt(i); continue; } _tempBullet = bulletList[i]; _tempBullet.update(); if (GameManager.me.currentScene != Scene.STATE.PLAY_BATTLE && UIPopupSkillPreview.isOpen == false) { continue; } _tempHitObject = _tempBullet.getHitObject(); if (_tempBullet.isCollisionCheckAtEndOnly || _tempBullet.canCollide == false || _tempBullet.delay > 0) { } else { //======= 곡사포가 아닌것만 체크. /////////////////////////////////////////////////////////////////////////////////// // 몬스터와 충돌 체크 int monsterCount = targetMonsterList.Count; isSkip = false; // 지속형 스킬일때 피격횟수를 매번 초기화하기위해. _tempBullet.checkTargetNum(); for (j = 0; j < monsterCount; ++j) { // if(GameManager.me.isPlaying == false) break; _tempMonster = targetMonsterList[j]; if (_tempMonster.isEnabled == false) { continue; // || _tempMonster.skipHitCheck } isHit = false; if (_tempBullet.isCircleColliderType) { _tempF = _tempBullet.targetRange + _tempMonster.damageRange; if (_tempF >= VectorUtil.DistanceXZ(_tempBullet.bTransformPosition, _tempMonster.cTransformPosition)) { isHit = true; } } else { if (_tempHitObject.intersectsBullet(_tempMonster.getHitObject())) { isHit = true; } } if (isHit) { //Log.log("_tempBullet : " + _tempBullet + "_tempMonster : " + _tempMonster.resourceId); _tempBullet.prevHp = _tempBullet.hp.Get(); if (_tempBullet.damageToCharacter != null) { _tempBullet.damageToCharacter(_tempMonster); } if (_tempMonster.isDeleteObject) //|| (_tempMonster.hp <= 0 && _tempMonster.invincible == false)) { //Log.log("==== _tempMonster.isDeleteObject !!"); _tempBullet.bulletData.hitDeadActionStart(_tempMonster.cTransformPosition); } if (_tempBullet.hp.Get() <= 0 && _tempBullet.invincible == false) { //_tempBullet.setDelete(); _tempBullet.destroy(); //playerBulletList.RemoveAt(i); isSkip = true; break; } else { if (_tempBullet.prevHp > _tempBullet.hp.Get() && _tempBullet.damageCheckTypeNo == 5) { int r = _tempBullet.retargetingRange.Get(); if (r > 0) { _tempBullet.startRetargeting(_tempMonster); } } } } } if (isSkip) { continue; } // 곡사포가 아닌것들 여기까지 ===== } // 화면 밖으로 벗어났는지 검사. if (_tempBullet.isOutSide()) // 화면 밖을 벗어났으면... { _tempBullet.setDelete(); } } _tempBullet = null; }
/// <summary> /// Query a regression algorithm and see how close it matches the training data. /// </summary> /// <param name="alg">The algorithm to evaluate.</param> /// <param name="theTrainingData">The training data.</param> public static void Query(IRegressionAlgorithm alg, IList <BasicData> theTrainingData) { foreach (BasicData data in theTrainingData) { double[] output = alg.ComputeRegression(data.Input); Console.WriteLine(VectorUtil.DoubleArrayToString(data.Input) + " -> " + VectorUtil.DoubleArrayToString(output) + ", Ideal: " + VectorUtil.DoubleArrayToString(data.Ideal)); } }
//public void copyInput(int nCode, IntPtr wParam, IntPtr lParam) //{ // Win32Util.INPUT input = new Win32Util.INPUT(); // input.Type = Win32Util.INPUT_TYPE.INPUT_MOUSE; // input.Data.Mouse.Flags = (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) ? 0 : KEYEVENTF_KEYUP; // Win32Util.SendInput(1,) //} private IntPtr interceptInput(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode == Win32Util.HC_ACTION) { newState = previousState; Win32Util.MSLLHOOKSTRUCT hookStruct = (Win32Util.MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(Win32Util.MSLLHOOKSTRUCT)); if (hookStruct.flags == (uint)Win32Util.LLHookFLags.LLMHF_INJECTED || hookStruct.flags == (uint)Win32Util.LLHookFLags.LLMHF_LOWER_IL_INJECTED) { return(Win32Util.CallNextHookEx(m_nativeHookPtr, nCode, wParam, lParam)); } if ((Win32Util.MouseMessages)wParam == Win32Util.MouseMessages.WM_LBUTTONDOWN) { newState.LMB = true; } if ((Win32Util.MouseMessages)wParam == Win32Util.MouseMessages.WM_LBUTTONUP) { newState.LMB = false; m_LMB_held = false; } else { //if we do not release LMB and it was previously also pressed if (previousState.LMB) { m_LMB_held = true; } } if ((Win32Util.MouseMessages)wParam == Win32Util.MouseMessages.WM_RBUTTONDOWN) { newState.RMB = true; } if ((Win32Util.MouseMessages)wParam == Win32Util.MouseMessages.WM_RBUTTONUP) { newState.RMB = false; m_RMB_held = false; } else { //if we do not release LMB and it was previously also pressed if (previousState.RMB) { m_LMB_held = true; } } bool moves = false; m_delta.X = 0; m_delta.Y = 0; if ((Win32Util.MouseMessages)wParam == Win32Util.MouseMessages.WM_MOUSEMOVE) { newState.pos.X = hookStruct.pt.x; newState.pos.Y = hookStruct.pt.y; m_delta.X = newState.pos.X - previousState.pos.X; m_delta.Y = newState.pos.Y - previousState.pos.Y; //Console.WriteLine("delta: x{0} y{1}", m_pos_delta.X, m_pos_delta.Y); moves = true; } //painting happened, we need to intercept if (m_LMB_held && moves) { ropeLogic.update(VectorUtil.toVec(newState.pos), VectorUtil.toVec(m_delta)); callCallbacks(ropeLogic.cursorPoint, ropeLogic.pullPoint, true); Win32Util.SetCursorPos(ropeLogic.cursorPoint.X, ropeLogic.cursorPoint.Y); /* * infinite loop of sending, recievieng this, and re-emmiting a new one!!! ** ** Win32Util.mouse_event((uint)Win32Util.MouseEventFlags.LEFTDOWN, ropeLogic.cursorPoint.X, ropeLogic.cursorPoint.Y, 0, 0); */ newState.pos = ropeLogic.cursorPoint; //Console.WriteLine("intercepting: x{0} y{1}", ropeLogic.cursorPoint.X, ropeLogic.cursorPoint.Y); previousState = newState; return((IntPtr)1); } else { //Console.WriteLine("no draw " + DateTime.Now.ToLongTimeString()); //Console.WriteLine("x{0} y{1} {2} {3}", m_pos.X, m_pos.Y, m_LMB_held ? "L" : " ", m_RMB_held ? "R" : " "); ropeLogic.reset(VectorUtil.toVec(newState.pos)); callCallbacks(ropeLogic.cursorPoint, ropeLogic.pullPoint, false); previousState = newState; return(Win32Util.CallNextHookEx(m_nativeHookPtr, nCode, wParam, lParam)); } /* Both methods to directly modify lParam do not "work" but they do change the native value seemingly. ** So I guess "passing" modified values like this is just not how this API is meant to work. ** A) Write any modifications to hookStruct back to the lParam via marshal ** Marshal.StructureToPtr(hookStruct, lParam, true); ** ** B) unsafe editing the pointer directly ** unsafe ** { ** Win32Util.MSLLHOOKSTRUCT* data = (Win32Util.MSLLHOOKSTRUCT*)lParam.ToPointer(); ** data->pt.x = 960; ** } ** ** So we Rather swallow the input by returning 1 ** and use SetCursorPos() or SendInput() to emit new signals. ** https://stackoverflow.com/questions/21928956/how-do-i-modify-keys-in-a-keyboardproc-hooking-procedure ** LLKHF_INJECTED may be to prevent a infinite loop of sending and reacting to your own messages */ //Console.WriteLine("Mouse hook: " + hookStruct.pt.x + ", " + hookStruct.pt.y); //Console.WriteLine("flag: " + hookStruct.flags); //if (hookStruct.flags == (uint)Win32Util.LLHookFLags.LLMHF_INJECTED) //{ // Console.WriteLine("is: " + hookStruct.flags + " LLMHF_INJECTED"); //} } Console.WriteLine("pass trough"); return(Win32Util.CallNextHookEx(m_nativeHookPtr, nCode, wParam, lParam)); }