public void Vector3ToStringTest() { string separator = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator; CultureInfo enUsCultureInfo = new CultureInfo("en-US"); Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f); string v1str = v1.ToString(); string expectedv1 = string.Format(CultureInfo.CurrentCulture , "<{1:G}{0} {2:G}{0} {3:G}>" , separator, 2, 3, 3.3); Assert.Equal(expectedv1, v1str); string v1strformatted = v1.ToString("c", CultureInfo.CurrentCulture); string expectedv1formatted = string.Format(CultureInfo.CurrentCulture , "<{1:c}{0} {2:c}{0} {3:c}>" , separator, 2, 3, 3.3); Assert.Equal(expectedv1formatted, v1strformatted); string v2strformatted = v1.ToString("c", enUsCultureInfo); string expectedv2formatted = string.Format(enUsCultureInfo , "<{1:c}{0} {2:c}{0} {3:c}>" , enUsCultureInfo.NumberFormat.NumberGroupSeparator, 2, 3, 3.3); Assert.Equal(expectedv2formatted, v2strformatted); string v3strformatted = v1.ToString("c"); string expectedv3formatted = string.Format(CultureInfo.CurrentCulture , "<{1:c}{0} {2:c}{0} {3:c}>" , separator, 2, 3, 3.3); Assert.Equal(expectedv3formatted, v3strformatted); }
// Update is called once per frame void Update() { if (Input.GetKeyDown (KeyCode.F1)) { CreateArray(); } if (Input.GetKeyDown (KeyCode.F2)) { foreach(GameObject go in hexGoArray){ Destroy(go); } } if (Input.GetKeyDown (KeyCode.F4)) { string name = ""; float newX = xindex*hexX; float newY = yindex*(-1*hexY); if((xindex+1)%2==0){ newY = newY + hexY/2; } Vector3 newPos = new Vector3(newX, newY, 0); if(GameObject.Find(newPos.ToString())){ Debug.Log("find by name " + newPos.ToString()+", xindex("+xindex+"), yindex("+yindex+")"); GameObject.Find(newPos.ToString()).SetActive(!GameObject.Find(newPos.ToString()).activeSelf); }else{ Debug.LogWarning("Not find by name " + newPos.ToString()+", xindex("+xindex+"), yindex("+yindex+")"); } } }
public void AddData(TidyFunctionalObject data) { Vector3 mapCoords = new Vector3(data.x,data.y,data.depth); if(!isInitialised){ for(int i = 0; i < mapData.Count; i++){ if(mapData[i].x == mapCoords.x && mapData[i].y == mapCoords.y && mapData[i].depth == mapCoords.z){ Debug.LogWarning("Already contained functional overlay data at: " + mapCoords.ToString() + ": removing."); mapData.RemoveAt(i); } } mapData.Add(data); } else{ if(mapDataTable.ContainsKey(mapCoords)){ mapDataTable.Remove(mapCoords); Debug.LogWarning("Already contained functional overlay data at: " + mapCoords.ToString() + ": removing."); } mapDataTable.Add(mapCoords,data); } }
void Update() { if (Input.GetMouseButtonDown(0)) { Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, cam.nearClipPlane); //Debug.Log ("Mouse pos : " + mousePos); newXAngle = Input.mousePosition.x / 100 -20; newYAngle = Input.mousePosition.y /100 - 10; //Debug.Log("Screen " + ScreenSize + " " + "Mouse" + Input.mousePosition.x); throwSpeed = new Vector3 (newXAngle, newYAngle, 20); ballPos = cam.ScreenToWorldPoint(mousePos) + new Vector3(0, 0, 0.1f); //Debug.Log ("Ball pos : " + ballPos.ToString("F7")); ballClone = Instantiate(ball, ballPos, transform.rotation) as GameObject; ballClone.GetComponent<Rigidbody>().AddForce(throwSpeed, ForceMode.Impulse); } if (X > 0 && Y > 0) { Vector3 tuioPos = new Vector3(X * 4055, Y * 2430, cam.nearClipPlane); // Works on my computer for x and y inverted, weird. //Vector3 tuioPos = new Vector3(Y * 4000, X * 2000, cam.nearClipPlane); Debug.Log ("Tuio pos : " + tuioPos.ToString("F7")); newXAngle = tuioPos.x / 130*1.4f -21; newYAngle = -tuioPos.y*tuioPos.y/100000+4.5f; Debug.Log("Screen " + ScreenSize + " " + "Tuio" + -tuioPos.x); Debug.Log("newYAngle" + newYAngle); throwSpeed = new Vector3 (newXAngle, newYAngle, 30); ballPos = cam.ScreenToWorldPoint(tuioPos) + new Vector3(0, 0, 0.1f); Debug.Log ("Ball pos : " + ballPos.ToString("F7")); // Works on my computer for x inverted, weird. //ballPos.x = -ballPos.x; ballPos.x = ballPos.x * 1.36f; ballPos.y = -ballPos.y * 1.33f + 20.15f; Debug.Log ("Ball pos : " + ballPos.ToString("F7")); ballClone = Instantiate(ball, ballPos, transform.rotation) as GameObject; // Color randColor = new Color(Random.Range(0, 255)/255, Random.Range(0, 255)/255, Random.Range(0, 255)/255); // ballClone.GetComponent<MeshRenderer>().material.SetColor("_Albedo", randColor); ballClone.GetComponent<Rigidbody>().AddForce(throwSpeed, ForceMode.Impulse); } }
void OnCollisionEnter(Collision coll) { ContactPoint contact = coll.contacts [0]; startPosition = contact.point; Debug.Log (startPosition.ToString () + coll.gameObject.ToString ()); Debug.Log (coll.gameObject.ToString ()); }
public void Update(float dTime) { targetPosition += (Game1.Instance.player.Get3Dpos() - targetPosition + new Vector3(0, 30, 0)) * 0.1f; targetPosition += new Vector3(Input.pad.ThumbSticks.Right.X, Input.pad.ThumbSticks.Right.Y, 0) * 10.0f; Vector3 shakeOffset = Vector3.Zero; if (shakeTimer > 0) { float shakeValue = shakeTimer / 500f; shakeOffset = new Vector3( -50 + Game1.random.Next(100), -50 + Game1.random.Next(100), -50 + Game1.random.Next(100)); shakeOffset *= 0.002f*dTime; shakeOffset *= shakeValue; shakeTimer -= (int)dTime; targetPosition += shakeOffset; Game1.Instance.debugTexts.Add("SHAKE:" + shakeOffset.ToString()); } position += (Game1.Instance.player.Get3Dpos() - position + new Vector3(0.0f, 30.0f, 80.0f+Input.pad.ThumbSticks.Right.LengthSquared()*60)) * 0.1f; //position += (targetPosition - position + new Vector3(0.0f, 10.0f, 80.0f)) * 0.1f; Game1.Instance.debugTexts.Add("Camera pos:" + position.ToString()); Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver2, aspectRatio, 1.0f, 1000.0f, out projection); Matrix.CreateLookAt(ref this.position, ref this.targetPosition, ref cameraUpVector, out view); view *= Matrix.CreateRotationZ(MathHelper.ToRadians(Input.pad.ThumbSticks.Right.X*15)); }
//Spawn AI at a random location void SpawnNow() { //Determine how many ai elements to spawn randomInt = Random.Range (1, 10); //Generate random X value randomXFloat = Random.Range (GameObject.Find ("Cube").GetComponent<CharacterMove> ().maxX, GameObject.Find ("Cube").GetComponent<CharacterMove> ().minX); //Generate Random Z value randomZFloat = Random.Range (GameObject.Find ("Cube").GetComponent<CharacterMove> ().minZ, GameObject.Find ("Cube").GetComponent<CharacterMove> ().maxZ); //Y Value randomYFloat = GameObject.Find ("Cube").GetComponent<CharacterMove> ().maxMinY; //Spawn vector spawnVector = new Vector3(randomXFloat, randomYFloat, randomZFloat); //Debug Debug.Log ("Spawn @ " + spawnVector.ToString ()); //Spawn the AI for (int i = 0; i <= randomInt; i++) { Instantiate(aiTest, new Vector3(spawnVector.x + 10 , spawnVector.y, spawnVector.z), Quaternion.identity); } }
public LevelBlock(string levelName, Vector3 coordinate, float scale) { mCoordinate = coordinate; mName = levelName + mCoordinate.ToString(); mHeightMapBlock = new HeightMapBlock(mName, coordinate * scale, new Quaternion(), new Vector3(scale)); }
public static Vector3 ColorVec3ToVector3(Vector3 color) { #if DEBUG Console.WriteLine(color.ToString() + " -> " + new Vector3((color.X / 255), (color.Y / 255), (color.Z / 255)).ToString()); #endif return new Vector3((color.X / 255), (color.Y / 255), (color.Z / 255)); }
public static bool AddNewLevelBlock(Level level, Vector3 coordinate, Texture2D heightMap, Texture2D alphaMap, string[] detailTextureNames, Vector2[] uvOffsets, Vector2[] uvScales) { if (level.Contains(coordinate)) { return false; } Color[] heightColors = new Color[HeightMapMesh.NUM_SIDE_VERTICES * HeightMapMesh.NUM_SIDE_VERTICES]; if (heightMap.Width != HeightMapMesh.NUM_SIDE_VERTICES || heightMap.Height != HeightMapMesh.NUM_SIDE_VERTICES) { RenderTarget2D resizedHeightMap = new RenderTarget2D(GraphicsManager.Device, HeightMapMesh.NUM_SIDE_VERTICES, HeightMapMesh.NUM_SIDE_VERTICES); GraphicsManager.Device.SetRenderTarget(resizedHeightMap); GraphicsManager.SpriteBatch.Begin(); GraphicsManager.SpriteBatch.Draw(heightMap, new Rectangle(0, 0, HeightMapMesh.NUM_SIDE_VERTICES, HeightMapMesh.NUM_SIDE_VERTICES), Color.White); GraphicsManager.SpriteBatch.End(); GraphicsManager.Device.SetRenderTarget(null); resizedHeightMap.GetData(heightColors); } else { heightMap.GetData(heightColors); } float[,] heights = new float[HeightMapMesh.NUM_SIDE_VERTICES, HeightMapMesh.NUM_SIDE_VERTICES]; for (int i = 0; i < heightColors.Length; i++) { heights[i % HeightMapMesh.NUM_SIDE_VERTICES, i / HeightMapMesh.NUM_SIDE_VERTICES] = ConvertColorToFloat(heightColors[i]); } if (alphaMap.Height != HeightMapMesh.NUM_SIDE_VERTICES * HeightMapMesh.NUM_SIDE_TEXELS_PER_QUAD || alphaMap.Width != HeightMapMesh.NUM_SIDE_VERTICES * HeightMapMesh.NUM_SIDE_TEXELS_PER_QUAD) { RenderTarget2D resizedAlphaMap = new RenderTarget2D(GraphicsManager.Device, HeightMapMesh.NUM_SIDE_VERTICES * HeightMapMesh.NUM_SIDE_TEXELS_PER_QUAD, HeightMapMesh.NUM_SIDE_VERTICES * HeightMapMesh.NUM_SIDE_TEXELS_PER_QUAD); GraphicsManager.Device.SetRenderTarget(resizedAlphaMap); GraphicsManager.SpriteBatch.Begin(); GraphicsManager.SpriteBatch.Draw(alphaMap, new Rectangle(0, 0, HeightMapMesh.NUM_SIDE_VERTICES * HeightMapMesh.NUM_SIDE_TEXELS_PER_QUAD, HeightMapMesh.NUM_SIDE_VERTICES * HeightMapMesh.NUM_SIDE_TEXELS_PER_QUAD), Color.White); GraphicsManager.SpriteBatch.End(); GraphicsManager.Device.SetRenderTarget(null); alphaMap = resizedAlphaMap; } HeightMapMesh heightMapMesh = new HeightMapMesh(heights, alphaMap, detailTextureNames, uvOffsets, uvScales); AssetLibrary.AddHeightMap(level.Name + coordinate.ToString(), heightMapMesh); level.AddNewBlock(coordinate); return true; }
// Use this for initialization void Start () { playerMovement = player.GetComponent<Move>(); initialPosition = transform.position; print ("Initial pos: " + initialPosition.ToString ()); print ("Dissaproval: " + disapproval.ToString ()); }
bool CheckPlacement(bool checkMatch) { bool results = true; bool tried = false; Vector3 location = currentLand.transform.position; for (int x = 0; x < 4; x++) { int ax = x % 2; int ay = (x + 1) % 2; if(x > 1) { ax *= -1; ay *= -1; } Vector3 key = new Vector3(location.x + ax, 0, location.z + ay ); GameObject target; if (placedLand.TryGetValue(key.ToString(), out target)) { tried = true; if(checkMatch) { results = results && currentLand.GetComponent<Tile>().TestPlacement(target, x); } else { results = true; } } } return results && tried; }
// Use this for initialization void Start() { isHit = false; animator = GetComponent<Animator>(); //animator.StartPlayback(); animator.SetBool("IsIdle", startIdle); isWalking = !startIdle; if(startIdle) { animator.Play("SpiderIdle", -1, 1f); } else { animator.Play("SpiderWalk", -1, 1f); } startPoint = transform.position; endPoint = new Vector3(transform.position.x + (startTowardsLeft ? -distanceToTravel: distanceToTravel) / 72f, transform.position.y, transform.position.z); totalDistanceTravelled = 0f; if(startTowardsLeft) { transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z); Vector3 tmp = endPoint; endPoint = startPoint; startPoint = tmp; startTowardsLeft = !startTowardsLeft; } Debug.Log(startPoint.ToString() + " " + endPoint.ToString()); }
/** * ??????????????????????? * */ public void setGravityDir(Vector3 newGravity) { float mass = m_Body ? m_Body.mass : 1.0f; Vector3 old = Vector3.Normalize(m_Gravity); Debug.Log("newGravity = " + newGravity.ToString()); m_Gravity = newGravity; Debug.Log("Gravity = " + m_Gravity.ToString()); m_Gravity *= m_gravityAcceleration; Debug.Log("Gravity = " + m_Gravity.ToString()); m_ConstForce.force = m_Gravity * mass; Debug.Log("Change Gravity Dir, from " + old.ToString() + " to " + newGravity.ToString()); if (m_Player) m_Player.OnChangeGravity(old, newGravity); }
public static void WriteLine(Vector3 vec) { vec.X = (float)Math.Round(vec.X, 3); vec.Y = (float)Math.Round(vec.Y, 3); vec.Z = (float)Math.Round(vec.Z, 3); WriteLine(vec.ToString()); }
// Use this for initialization void Start() { Debug.Log("Start"); controller = new Controller(); if (!controller.IsGestureEnabled(Gesture.GestureType.TYPE_SWIPE)) { Debug.Log("Enabled swipe"); // controller.EnableGesture(Gesture.GestureType.TYPE_SWIPE); } if (!controller.IsGestureEnabled(Gesture.GestureType.TYPE_SCREEN_TAP)) { Debug.Log("Enabled screen tap"); controller.EnableGesture(Gesture.GestureType.TYPE_SCREEN_TAP); } if (!controller.IsGestureEnabled(Gesture.GestureType.TYPE_KEY_TAP)) { Debug.Log("Enabled key tap"); controller.EnableGesture(Gesture.GestureType.TYPE_KEY_TAP); } button = GameObject.Find("Button"); //button = FindObjectOfType(); buttonPos = button.transform.position.normalized; Debug.Log(System.String.Format("Button pos: {0}", buttonPos.ToString())); // buttonPos = new Vector(position.x, position.y, position.z); }
public double getPerlin(Vector3 point) { DebugOutput.Shout(point.ToString()); int xi = (int)point.x & 255; int yi = (int)point.y & 255; int zi = (int)point.z & 255; DebugOutput.Shout("xi " + xi.ToString()); DebugOutput.Shout("yi " + yi.ToString()); DebugOutput.Shout("zi " + zi.ToString()); float XF = point.x - (int)point.x; float YF = point.y - (int)point.y; float ZF = point.z - (int)point.z; DebugOutput.Shout("XF " + XF.ToString()); DebugOutput.Shout("YF " + YF.ToString()); DebugOutput.Shout("ZF " + ZF.ToString()); double u = fade(XF); double v = fade(YF); double w = fade(ZF); DebugOutput.Shout("u " + u.ToString()); DebugOutput.Shout("v " + v.ToString()); DebugOutput.Shout("w " + w.ToString()); return 0.0; }
void Update() { elapsed += Time.deltaTime; if (elapsed > 1f) { elapsed = 0f; var sb = new StringBuilder(); elapsed = 0f; Vector3 v = new Vector3(2, 3, 6); Vector3 w = new Vector3(7, 23, 1); var n = v.normalized; object[] arr = new object[] { n.x, n.y, n.z }; Debug.Log(sb.AppendFormat("v.normalized = ({0}, {1}, {2})", arr).ToString()); sb.Remove(0, sb.Length); var cross = Vector3.Cross(v, w); arr = new object[] { cross.x, cross.y, cross.z }; Debug.Log(sb.AppendFormat("Cross(v, w) = ({0}, {1}, {2})", arr).ToString()); Debug.Log("v.magnitude = " + v.magnitude); Debug.Log("w.magnitude = " + w.magnitude); Debug.Log("Dot(v, w) = " + Vector3.Dot(v, w)); Debug.Log("Angle(v, w) = " + Vector3.Angle(v, w)); var proj = Vector3.Project(v, w); Debug.Log("Project(v,w) = " + proj.ToString()); v.Normalize(); w.Normalize(); Debug.Log("normalized v = " + v.ToString()); Debug.Log("normalized w = " + w.ToString()); } }
public void BlocklyMove( Vector3 direction ) { GetComponent<CharacterController>().Move ( direction ); GetComponent<CharacterController>().Move ( Physics.gravity ); // apply gravity Debug.Log (actionNumber.ToString () + ": BlocklyMove" + direction.ToString () ); actionNumber++; }
public GameObject SpawnEnemy(string name, Vector3 position) { GameManager.WriteMessage ("Spawning " + name + " at " + position.ToString ()); NetworkViewID id = Network.AllocateViewID (); if (Network.isServer) networkView.RPC ("SpawnEnemyRPC", RPCMode.Others, name, position, id); return SpawnEnemy (name, position, id); }
private GameObject createPiece(GameObject prefab, Vector3 position, GameObject containerGameobject) { GameObject go = Instantiate(prefab) as GameObject; go.transform.position = position; go.transform.parent = containerGameobject.transform; go.name = prefab.name + " " + position.ToString(); return go; }
// Use this for initialization void Start() { isActive = true; bd = this.gameObject.GetComponent<SphereCollider> ().bounds; pos = this.gameObject.transform.position; Debug.Log ("REAL POS: " + pos.ToString()); //this.gameObject.SetActive (false); }
public float getReduction(Vector3 p) { if (it.isActive && it.bd.Contains(p)) { Debug.Log (-3000.0f / Vector3.Distance(p, it.pos) + " " + p.ToString ()); return -3000.0f / Vector3.Distance(p, it.pos); } return 0.0f; }
private Vector3 ScreenPositionToWorldPosition(Vector2 screenPos) { Vector3 result; Ray tempRay = Camera.main.ScreenPointToRay(screenPos); result = tempRay.GetPoint(9.0f); result = new Vector3(result.x, result.y, 0); print(result.ToString()); return result; }
public void SetTarget(Vector3 a) { if(!target.Equals(a)){ Debug.Log("Set Target to: " + a.ToString()); target = a; turning = true; RoomPiece.cameraChanging = true; } }
void rot() { rotate += rotatespeed * Time.deltaTime; scorecount += rotatespeed * Time.deltaTime; if (scorecount > 1) { status.ScoreCounter += (int)scorecount; scorecount = 0f; } Debug.Log (rotate); Vector3 rot = new Vector3 (); rot = transform.localEulerAngles; Debug.Log (rot.ToString ()); rot.x = rotate; rot.y = 90f; rot.z = -90f; Debug.Log (rot.ToString ()); transform.localEulerAngles = rot; }
public void SetTarget(Vector3 location) { // Set the new target print("location: " + location.ToString()); target.transform.position = location; // Initialise pathfinding order if(selectedUnit) selectedUnit.SetNavTarget(location); }
void TestWTI(Vector3 testVector) { DebugOutput.Shout("Testing WTI: " + testVector.ToString() + " equals " + wti.TranslateWorldPoint(testVector)); int index = wti.GetIndexAtWorldPoint2(testVector); // DebugOutput.Shout("TestValue: " + worldTree.indices[index].ToString() + "at index: " + index.ToString()); // TestValue = wti.GetValueAtWorldPoint(Vector3.zero, true); //DebugOutput.Shout("expanded testvalue: " + TestValue.ToString()); }
public static LookAtObject Begin( Transform parent, Vector3 target, float lookSpeed ) { GameObject obj = new GameObject( "[LookAtObject] Chase-> " + target.ToString() ); var instance = obj.AddComponent<LookAtObject>(); obj.transform.parent = parent; obj.transform.localPosition = Vector3.zero; instance.refTargetPosition = target; instance.lookSpeed = lookSpeed; return instance; }
bool isTapped(Vector3 acc) { bool magnitudeOk = acc.magnitude > magnitude_thresh; bool axisOk = (Mathf.Pow (acc.y, 2) > (Mathf.Pow (acc.x,2) + Mathf.Pow (acc.z,2))); bool directionOk = acc.y < 0; if (magnitudeOk && axisOk && directionOk) { print ("Tap! " + acc.magnitude.ToString() + acc.ToString()); return true; } return false; }
protected void InternalUpdateAngularVelocity() { try { HkRigidBody havokBody = PhysicsBody; if (havokBody == null) { return; } if (SandboxGameAssemblyWrapper.IsDebugging) { LogManager.APILog.WriteLineAndConsole(this.GetType().Name + " - Changing angular velocity of '" + Name + "' from '" + havokBody.AngularVelocity.ToString() + "' to '" + m_angularVelocity.ToString() + "'"); } havokBody.AngularVelocity = m_angularVelocity; } catch (Exception ex) { LogManager.ErrorLog.WriteLine(ex); } }
public string ToString(string format) { return(string.Format("Segment3(a: {0}, b: {1})", a.ToString(format), b.ToString(format))); }
/// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { return(string.Format(CultureInfo.CurrentCulture, "Minimum:{0} Maximum:{1}", Minimum.ToString(), Maximum.ToString())); }
public override string ToString() { return("Position " + position.ToString() + " and Rotation " + rotation.ToString()); }
public override string ToString() { return(string.Format("{0} {1} {2}", id, unk0.ToString(), unk1.ToString())); }
public static IEnumerator Strike(float initialDelay, float delayBetweenStrikes, int strikeCount, float damageIntensity, int range, Vector3 startPoint) { const float DAMAGE = 200; // timer Airstrikes.Instance.Vectors.Add(startPoint); if (Airstrikes.Instance.Configuration.Instance.GlobalMessageColor.StartsWith("#")) { Color?hexColor = UnturnedChat.GetColorFromHex(Airstrikes.Instance.Configuration.Instance.GlobalMessageColor); UnturnedChat.Say(Airstrikes.Instance.Translate("global_airstrike_sec", startPoint.ToString(), initialDelay), hexColor ?? default(Color)); } else { UnturnedChat.Say(Airstrikes.Instance.Translate("global_airstrike_sec", startPoint.ToString(), initialDelay), UnturnedChat.GetColorFromName(Airstrikes.Instance.Configuration.Instance.GlobalMessageColor, Color.green)); } yield return(new WaitForSeconds(initialDelay)); if (Airstrikes.Instance.Configuration.Instance.GlobalMessageColor.StartsWith("#")) { Color?hexColor = UnturnedChat.GetColorFromHex(Airstrikes.Instance.Configuration.Instance.GlobalMessageColor); UnturnedChat.Say(Airstrikes.Instance.Translate("global_airstrike_now", startPoint.ToString()), hexColor ?? default(Color)); } else { UnturnedChat.Say(Airstrikes.Instance.Translate("global_airstrike_now", startPoint.ToString()), UnturnedChat.GetColorFromName(Airstrikes.Instance.Configuration.Instance.GlobalMessageColor, Color.green)); } yield return(new WaitForSeconds(3f)); Airstrikes.Instance.Vectors.Remove(startPoint); // strike... for (int i = 0; i < (strikeCount + 1); i++) { yield return(new WaitForSeconds(delayBetweenStrikes)); Ray impactRay = new Ray(new Vector3(UnityEngine.Random.Range(startPoint.x - range, startPoint.x + range), startPoint.y + 50, UnityEngine.Random.Range(startPoint.z - range, startPoint.z + range)), Vector3.down); if (Physics.Raycast(impactRay, out RaycastHit hit)) { EffectManager.sendEffect(20, EffectManager.INSANE, hit.point); DamageTool.explode(hit.point, damageIntensity, EDeathCause.MISSILE, CSteamID.Nil, DAMAGE, DAMAGE, DAMAGE, DAMAGE, DAMAGE, DAMAGE, DAMAGE, DAMAGE); Airstrikes.WriteDebug(hit.point.ToString()); } } }
private string GetInfo(WorldSerialization blob) { // Resolution of the terrain height and water maps var meshResolution = Mathf.NextPowerOfTwo((int)(blob.world.size * 0.50f)) + 1; // Resolution of the terrain splat, topology, biome and alpha maps var textureResolution = Mathf.NextPowerOfTwo((int)(blob.world.size * 0.50f)); // The dimensions of the terrain object, Y always goes from -500 to +500, X and Z from -extents to +extents var terrainSize = new Vector3(blob.world.size, 1000, blob.world.size); // The position of the terrain object, chosen so world origin is always at the center of the terrain bounds var terrainPosition = -0.5f * terrainSize; // Terrain mesh height values (16 bit) // Indexed [z, x] var terrainMap = new TerrainMap <short>(blob.GetMap("terrain").data, 1); // World height values (16 bit) // Indexed [z, x] // Used to sample the height at which to spawn grass and decor at // Can include both terrain and other meshes like for example cliffs var heightMap = new TerrainMap <short>(blob.GetMap("height").data, 1); // Water map (16 bit) // Indexed [z, x] // Includes both the ocean plane at zero level and any rivers var waterMap = new TerrainMap <short>(blob.GetMap("water").data, 1); // Alpha map (8 bit) // Indexed [z, x] // Zero to render parts of the terrain invisible var alphaMap = new TerrainMap <byte>(blob.GetMap("alpha").data, 1); // Splat map (8 bit, 8 channels) // Indexed [c, z, x] (see TerrainSplat class) // Sum of all channels should be normalized to 255 var splatMap = new TerrainMap <byte>(blob.GetMap("splat").data, 8); // Biome map (8 bit, 4 channels) // Indexed [c, z, x] (see TerrainBiome class) // Sum of all channels should be normalized to 255 var biomeMap = new TerrainMap <byte>(blob.GetMap("biome").data, 4); // Topology map (32 bit) // Indexed [z, x] (see TerrainTopology class) // Used as a bit mask, multiple topologies can be set in one location var topologyMap = new TerrainMap <int>(blob.GetMap("topology").data, 1); int x = 0; int z = 0; var sb = new StringBuilder(); sb.AppendLine("Info"); sb.Append("\tPosition: "); sb.AppendLine(terrainPosition.ToString()); sb.Append("\tSize: "); sb.AppendLine(terrainSize.ToString()); sb.Append("\tMesh Resolution: "); sb.AppendLine(meshResolution.ToString()); sb.Append("\tTexture Resolution: "); sb.AppendLine(textureResolution.ToString()); sb.AppendLine(); sb.AppendLine("Terrain Map"); sb.Append("\t"); sb.AppendLine(BitUtility.Short2Float(terrainMap[z, x]).ToString()); sb.AppendLine(); sb.AppendLine("Height Map"); sb.Append("\t"); sb.AppendLine(BitUtility.Short2Float(heightMap[z, x]).ToString()); sb.AppendLine(); sb.AppendLine("Water Map"); sb.Append("\t"); sb.AppendLine(BitUtility.Short2Float(waterMap[z, x]).ToString()); sb.AppendLine(); sb.AppendLine("Alpha Map"); sb.Append("\t"); sb.AppendLine(BitUtility.Byte2Float(alphaMap[z, x]).ToString()); sb.AppendLine(); sb.AppendLine("Splat Map"); sb.Append("\tDirt: "); sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.DIRT_IDX, z, x]).ToString()); sb.Append("\tSnow: "); sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.SNOW_IDX, z, x]).ToString()); sb.Append("\tSand: "); sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.SAND_IDX, z, x]).ToString()); sb.Append("\tRock: "); sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.ROCK_IDX, z, x]).ToString()); sb.Append("\tGrass: "); sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.GRASS_IDX, z, x]).ToString()); sb.Append("\tForest: "); sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.FOREST_IDX, z, x]).ToString()); sb.Append("\tStones: "); sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.STONES_IDX, z, x]).ToString()); sb.Append("\tGravel: "); sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.GRAVEL_IDX, z, x]).ToString()); sb.AppendLine(); sb.AppendLine("Biome Map"); sb.Append("\tArid: "); sb.AppendLine(BitUtility.Byte2Float(biomeMap[TerrainBiome.ARID_IDX, z, x]).ToString()); sb.Append("\tTemperate: "); sb.AppendLine(BitUtility.Byte2Float(biomeMap[TerrainBiome.TEMPERATE_IDX, z, x]).ToString()); sb.Append("\tTundra: "); sb.AppendLine(BitUtility.Byte2Float(biomeMap[TerrainBiome.TUNDRA_IDX, z, x]).ToString()); sb.Append("\tArctic: "); sb.AppendLine(BitUtility.Byte2Float(biomeMap[TerrainBiome.ARCTIC_IDX, z, x]).ToString()); sb.AppendLine(); sb.AppendLine("Topology Map"); sb.Append("\tField: "); sb.AppendLine((topologyMap[z, x] & TerrainTopology.FIELD) != 0 ? "yes" : "no"); sb.Append("\tBeach: "); sb.AppendLine((topologyMap[z, x] & TerrainTopology.BEACH) != 0 ? "yes" : "no"); sb.Append("\tForest: "); sb.AppendLine((topologyMap[z, x] & TerrainTopology.FOREST) != 0 ? "yes" : "no"); sb.Append("\tOcean: "); sb.AppendLine((topologyMap[z, x] & TerrainTopology.OCEAN) != 0 ? "yes" : "no"); sb.Append("\tLake: "); sb.AppendLine((topologyMap[z, x] & TerrainTopology.LAKE) != 0 ? "yes" : "no"); sb.AppendLine(); sb.AppendLine("Paths"); sb.Append("\t"); sb.Append(blob.world.paths.Count); return(sb.ToString()); }
public virtual OSDMap Pack() { // m_log.InfoFormat("[CHILDAGENTDATAUPDATE] Pack data"); OSDMap args = new OSDMap(); args["message_type"] = OSD.FromString("AgentData"); args["region_id"] = OSD.FromString(RegionID.ToString()); args["circuit_code"] = OSD.FromString(CircuitCode.ToString()); args["agent_uuid"] = OSD.FromUUID(AgentID); args["session_uuid"] = OSD.FromUUID(SessionID); args["position"] = OSD.FromString(Position.ToString()); args["velocity"] = OSD.FromString(Velocity.ToString()); args["center"] = OSD.FromString(Center.ToString()); args["size"] = OSD.FromString(Size.ToString()); args["at_axis"] = OSD.FromString(AtAxis.ToString()); args["left_axis"] = OSD.FromString(LeftAxis.ToString()); args["up_axis"] = OSD.FromString(UpAxis.ToString()); //backwards compatibility args["changed_grid"] = OSD.FromBoolean(SenderWantsToWaitForRoot); args["wait_for_root"] = OSD.FromBoolean(SenderWantsToWaitForRoot); args["far"] = OSD.FromReal(Far); args["aspect"] = OSD.FromReal(Aspect); if ((Throttles != null) && (Throttles.Length > 0)) { args["throttles"] = OSD.FromBinary(Throttles); } args["locomotion_state"] = OSD.FromString(LocomotionState.ToString()); args["head_rotation"] = OSD.FromString(HeadRotation.ToString()); args["body_rotation"] = OSD.FromString(BodyRotation.ToString()); args["control_flags"] = OSD.FromString(ControlFlags.ToString()); args["energy_level"] = OSD.FromReal(EnergyLevel); args["god_level"] = OSD.FromString(GodLevel.ToString()); args["always_run"] = OSD.FromBoolean(AlwaysRun); args["prey_agent"] = OSD.FromUUID(PreyAgent); args["agent_access"] = OSD.FromString(AgentAccess.ToString()); args["active_group_id"] = OSD.FromUUID(ActiveGroupID); if ((Groups != null) && (Groups.Length > 0)) { OSDArray groups = new OSDArray(Groups.Length); foreach (AgentGroupData agd in Groups) { groups.Add(agd.PackUpdateMessage()); } args["groups"] = groups; } if ((Anims != null) && (Anims.Length > 0)) { OSDArray anims = new OSDArray(Anims.Length); foreach (Animation aanim in Anims) { anims.Add(aanim.PackUpdateMessage()); } args["animations"] = anims; } if (DefaultAnim != null) { args["default_animation"] = DefaultAnim.PackUpdateMessage(); } if (AnimState != null) { args["animation_state"] = AnimState.PackUpdateMessage(); } if (Appearance != null) { args["packed_appearance"] = Appearance.Pack(); } //if ((AgentTextures != null) && (AgentTextures.Length > 0)) //{ // OSDArray textures = new OSDArray(AgentTextures.Length); // foreach (UUID uuid in AgentTextures) // textures.Add(OSD.FromUUID(uuid)); // args["agent_textures"] = textures; //} // The code to pack textures, visuals, wearables and attachments // should be removed; packed appearance contains the full appearance // This is retained for backward compatibility only if (Appearance.Texture != null) { byte[] rawtextures = Appearance.Texture.GetBytes(); args["texture_entry"] = OSD.FromBinary(rawtextures); } if ((Appearance.VisualParams != null) && (Appearance.VisualParams.Length > 0)) { args["visual_params"] = OSD.FromBinary(Appearance.VisualParams); } // We might not pass this in all cases... if ((Appearance.Wearables != null) && (Appearance.Wearables.Length > 0)) { OSDArray wears = new OSDArray(Appearance.Wearables.Length); foreach (AvatarWearable awear in Appearance.Wearables) { wears.Add(awear.Pack()); } args["wearables"] = wears; } List <AvatarAttachment> attachments = Appearance.GetAttachments(); if ((attachments != null) && (attachments.Count > 0)) { OSDArray attachs = new OSDArray(attachments.Count); foreach (AvatarAttachment att in attachments) { attachs.Add(att.Pack()); } args["attachments"] = attachs; } // End of code to remove if ((Controllers != null) && (Controllers.Length > 0)) { OSDArray controls = new OSDArray(Controllers.Length); foreach (ControllerData ctl in Controllers) { controls.Add(ctl.PackUpdateMessage()); } args["controllers"] = controls; } if ((CallbackURI != null) && (!CallbackURI.Equals(""))) { args["callback_uri"] = OSD.FromString(CallbackURI); } // Attachment objects for fatpack messages if (AttachmentObjects != null) { int i = 0; OSDArray attObjs = new OSDArray(AttachmentObjects.Count); foreach (ISceneObject so in AttachmentObjects) { OSDMap info = new OSDMap(4); info["sog"] = OSD.FromString(so.ToXml2()); info["extra"] = OSD.FromString(so.ExtraToXmlString()); info["modified"] = OSD.FromBoolean(so.HasGroupChanged); try { info["state"] = OSD.FromString(AttachmentObjectStates[i++]); } catch (IndexOutOfRangeException) { m_log.WarnFormat("[CHILD AGENT DATA]: scripts list is shorter than object list."); } attObjs.Add(info); } args["attach_objects"] = attObjs; } args["parent_part"] = OSD.FromUUID(ParentPart); args["sit_offset"] = OSD.FromString(SitOffset.ToString()); return(args); }
/// <summary> /// Pack AgentCircuitData into an OSDMap for transmission over LLSD XML or LLSD json /// </summary> /// <returns>map of the agent circuit data</returns> public OSDMap PackAgentCircuitData() { OSDMap args = new OSDMap(); args["agent_id"] = OSD.FromUUID(AgentID); args["base_folder"] = OSD.FromUUID(BaseFolder); args["caps_path"] = OSD.FromString(CapsPath); if (ChildrenCapSeeds != null) { OSDArray childrenSeeds = new OSDArray(ChildrenCapSeeds.Count); foreach (KeyValuePair <ulong, string> kvp in ChildrenCapSeeds) { OSDMap pair = new OSDMap(); pair["handle"] = OSD.FromString(kvp.Key.ToString()); pair["seed"] = OSD.FromString(kvp.Value); childrenSeeds.Add(pair); } if (ChildrenCapSeeds.Count > 0) { args["children_seeds"] = childrenSeeds; } } args["child"] = OSD.FromBoolean(child); args["circuit_code"] = OSD.FromString(circuitcode.ToString()); args["first_name"] = OSD.FromString(firstname); args["last_name"] = OSD.FromString(lastname); args["inventory_folder"] = OSD.FromUUID(InventoryFolder); args["secure_session_id"] = OSD.FromUUID(SecureSessionID); args["session_id"] = OSD.FromUUID(SessionID); args["service_session_id"] = OSD.FromString(ServiceSessionID); args["start_pos"] = OSD.FromString(startpos.ToString()); args["client_ip"] = OSD.FromString(IPAddress); args["viewer"] = OSD.FromString(Viewer); args["channel"] = OSD.FromString(Channel); args["mac"] = OSD.FromString(Mac); args["id0"] = OSD.FromString(Id0); if (Appearance != null) { args["appearance_serial"] = OSD.FromInteger(Appearance.Serial); OSDMap appmap = Appearance.Pack(); args["packed_appearance"] = appmap; } if (ServiceURLs != null && ServiceURLs.Count > 0) { OSDArray urls = new OSDArray(ServiceURLs.Count * 2); foreach (KeyValuePair <string, object> kvp in ServiceURLs) { //System.Console.WriteLine("XXX " + kvp.Key + "=" + kvp.Value); urls.Add(OSD.FromString(kvp.Key)); urls.Add(OSD.FromString((kvp.Value == null) ? string.Empty : kvp.Value.ToString())); } args["service_urls"] = urls; } return(args); }
/// <summary> /// Draw a circle around the mouse showing the zone of painting /// </summary> void drawGizmo() { if (!enableSceneGizmo) { return; } if (isPainting) { Handles.color = Color.red; } else { Handles.color = Color.green; } Vector3 pos = currentMousePos; //rotate = Quaternion.AngleAxis(90, mouseHitPoint.normal) * Quaternion.AngleAxis(90, Vector3.right); if (mouseHitPoint.transform) { if (paintPosition == null) { paintPosition = new GameObject(TEMPORARY_OBJECT_NAME).transform; paintPosition.gameObject.AddComponent <EditorSceneGizmo>(); } paintPosition.rotation = mouseHitPoint.transform.rotation; paintPosition.forward = mouseHitPoint.normal; if (param.mode == PaintMode.Forced) { pos.y = param.heightForced; } if (param.gizmoNormal) { Handles.ArrowCap(3, mouseHitPoint.point, paintPosition.rotation, gizmoNormalLenght); } if (param.gizmoCircle) { Handles.CircleCap(2, currentMousePos, paintPosition.rotation, param.size); } paintPosition.up = mouseHitPoint.normal; } Handles.BeginGUI(); GUIStyle style = new GUIStyle(); style.normal.textColor = Color.black; GUILayout.BeginArea(new Rect(currentEvent.mousePosition.x + 10, currentEvent.mousePosition.y + 10, 250, 100)); if (param.gizmoSize) { GUILayout.TextField("Size " + param.size, style); } if (param.gizmoDensity) { GUILayout.TextField("Density " + param.density, style); } if (param.gizmoHeight) { GUILayout.TextField("Height " + currentMousePos.y, style); } if (param.gizmoLayer) { GUILayout.TextField("Layer " + (mouseHitPoint.collider ? LayerMask.LayerToName(mouseHitPoint.collider.gameObject.layer) : "none"), style); } if (param.gizmoName) { GUILayout.TextField("Name " + (mouseHitPoint.collider ? mouseHitPoint.collider.name : "none"), style); } if (param.gizmoPosition) { GUILayout.TextField("Position " + currentMousePos.ToString(), style); } if (param.mode == PaintMode.Forced) { GUILayout.TextField("Force-Height " + param.heightForced, style); } GUILayout.EndArea(); Handles.EndGUI(); DrawingSceneSpawner(); }
public void RpcJumpBall(Vector3 forceVector) { GetComponent <Rigidbody>().AddForce(forceVector, ForceMode.Impulse); Debug.Log("Jump (" + forceVector.ToString() + ")"); }
public static Chunk[] SetStructure(ref WorldResources worldRes, BlockStructure structure) { List <Chunk> modifiedChunks = new List <Chunk>(); int x = ((int)Mathf.Ceil(16 * ((structure.BuildPointer.x / 16) - ((int)(structure.BuildPointer.x / 16))) + 0.5f) - 1); int Height = (int)Mathf.Ceil(255 * ((structure.BuildPointer.y / 255) - ((int)(structure.BuildPointer.y / 255))) + 0.5f) - 1; int z = (int)Mathf.Ceil(16 * ((structure.BuildPointer.z / 16) - ((int)(structure.BuildPointer.z / 16))) + 0.5f) - 1; int chunkX = (int)(structure.BuildPointer.x / 16f); int chunkZ = (int)(structure.BuildPointer.z / 16f); Chunk selectedChunk; Vector3 spawnPointer; for (int i = 0; i < structure.Structure.Length; i++) { int chunkMx = 0; int chunkMz = 0; spawnPointer = new Vector3((structure.Structure[i].WorldPos.x + x), (structure.Structure[i].WorldPos.y + Height), (structure.Structure[i].WorldPos.z + z)); if (spawnPointer.x >= 16) { chunkMx += (int)(spawnPointer.x / 16f); spawnPointer.x = spawnPointer.x - 16; } if (spawnPointer.z >= 16) { spawnPointer.z = spawnPointer.z - 16; chunkMz += (int)(spawnPointer.z / 16f); } if (spawnPointer.x < 0) { spawnPointer.x = -(spawnPointer.x - 16); chunkMx -= (int)(Mathf.Abs(spawnPointer.x) / 16f); //Debug.Log($"{Mathf.Abs(spawnPointer.x)} / 16 = {chunkX + chunkMx} ; {spawnPointer.x}"); } if (spawnPointer.z < 0) { spawnPointer.z = -(spawnPointer.z - 16); chunkMz -= (int)(Mathf.Abs(spawnPointer.z) / 16f); } if ((chunkZ + chunkMz) < 0 || (chunkZ + chunkMz) >= worldRes.VMG.ChunksRenderDistance || (chunkX + chunkMx) < 0 || (chunkX + chunkMx) >= worldRes.VMG.ChunksRenderDistance) { continue; } selectedChunk = worldRes.WorldMap[chunkZ + chunkMz, chunkX + chunkMx]; try { selectedChunk.ChunkMap[(int)spawnPointer.y, (int)spawnPointer.z, (int)spawnPointer.x] = structure.Structure[i].ID; } catch { Debug.Log($"{spawnPointer.ToString()}"); } if (!IsChunkInList(ref modifiedChunks, ref selectedChunk) == true) { modifiedChunks.Add(selectedChunk); } } return(modifiedChunks.ToArray()); }
/// <summary> /// Pack AgentCircuitData into an OSDMap for transmission over LLSD XML or LLSD json /// </summary> /// <returns>map of the agent circuit data</returns> public OSDMap PackAgentCircuitData() { OSDMap args = new OSDMap(); args["agent_id"] = OSD.FromUUID(AgentID); args["base_folder"] = OSD.FromUUID(BaseFolder); args["caps_path"] = OSD.FromString(CapsPath); if (ChildrenCapSeeds != null) { OSDArray childrenSeeds = new OSDArray(ChildrenCapSeeds.Count); foreach (KeyValuePair <ulong, string> kvp in ChildrenCapSeeds) { OSDMap pair = new OSDMap(); pair["handle"] = OSD.FromString(kvp.Key.ToString()); pair["seed"] = OSD.FromString(kvp.Value); childrenSeeds.Add(pair); } if (ChildrenCapSeeds.Count > 0) { args["children_seeds"] = childrenSeeds; } } args["child"] = OSD.FromBoolean(child); args["circuit_code"] = OSD.FromString(circuitcode.ToString()); args["first_name"] = OSD.FromString(firstname); args["last_name"] = OSD.FromString(lastname); args["inventory_folder"] = OSD.FromUUID(InventoryFolder); args["secure_session_id"] = OSD.FromUUID(SecureSessionID); args["session_id"] = OSD.FromUUID(SessionID); args["service_session_id"] = OSD.FromString(ServiceSessionID); args["start_pos"] = OSD.FromString(startpos.ToString()); args["appearance_serial"] = OSD.FromInteger(Appearance.Serial); args["viewer"] = OSD.FromString(Viewer); if (Appearance != null) { //System.Console.WriteLine("XXX Before packing Wearables"); if ((Appearance.Wearables != null) && (Appearance.Wearables.Length > 0)) { OSDArray wears = new OSDArray(Appearance.Wearables.Length * 2); foreach (AvatarWearable awear in Appearance.Wearables) { wears.Add(OSD.FromUUID(awear.ItemID)); wears.Add(OSD.FromUUID(awear.AssetID)); //System.Console.WriteLine("XXX ItemID=" + awear.ItemID + " assetID=" + awear.AssetID); } args["wearables"] = wears; } //System.Console.WriteLine("XXX Before packing Attachments"); Dictionary <int, UUID[]> attachments = Appearance.GetAttachmentDictionary(); if ((attachments != null) && (attachments.Count > 0)) { OSDArray attachs = new OSDArray(attachments.Count); foreach (KeyValuePair <int, UUID[]> kvp in attachments) { AttachmentData adata = new AttachmentData(kvp.Key, kvp.Value[0], kvp.Value[1]); attachs.Add(adata.PackUpdateMessage()); //System.Console.WriteLine("XXX att.pt=" + kvp.Key + "; itemID=" + kvp.Value[0] + "; assetID=" + kvp.Value[1]); } args["attachments"] = attachs; } } if (ServiceURLs != null && ServiceURLs.Count > 0) { OSDArray urls = new OSDArray(ServiceURLs.Count * 2); foreach (KeyValuePair <string, object> kvp in ServiceURLs) { //System.Console.WriteLine("XXX " + kvp.Key + "=" + kvp.Value); urls.Add(OSD.FromString(kvp.Key)); urls.Add(OSD.FromString((kvp.Value == null) ? string.Empty : kvp.Value.ToString())); } args["service_urls"] = urls; } return(args); }
// ------------------------------------------- /* * Get a description text of the variable */ public override string GetInformation() { return(m_name + ":" + m_value.ToString()); }
/// <summary> /// Updates the userpicks /// </summary> /// <param name='remoteClient'> /// Remote client. /// </param> /// <param name='pickID'> /// Pick I. /// </param> /// <param name='creatorID'> /// the creator of the pick /// </param> /// <param name='topPick'> /// Top pick. /// </param> /// <param name='name'> /// Name. /// </param> /// <param name='desc'> /// Desc. /// </param> /// <param name='snapshotID'> /// Snapshot I. /// </param> /// <param name='sortOrder'> /// Sort order. /// </param> /// <param name='enabled'> /// Enabled. /// </param> public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc, UUID snapshotID, int sortOrder, bool enabled) { //TODO: See how this works with NPC, May need to test m_log.DebugFormat("[PROFILES]: Start PickInfoUpdate Name: {0} PickId: {1} SnapshotId: {2}", name, pickID.ToString(), snapshotID.ToString()); UserProfilePick pick = new UserProfilePick(); string serverURI = string.Empty; GetUserProfileServerURI(remoteClient.AgentId, out serverURI); ScenePresence p = FindPresence(remoteClient.AgentId); Vector3 avaPos = p.AbsolutePosition; // Getting the global position for the Avatar Vector3 posGlobal = new Vector3(remoteClient.Scene.RegionInfo.WorldLocX + avaPos.X, remoteClient.Scene.RegionInfo.WorldLocY + avaPos.Y, avaPos.Z); string landParcelName = "My Parcel"; UUID landParcelID = p.currentParcelUUID; ILandObject land = p.Scene.LandChannel.GetLandObject(avaPos.X, avaPos.Y); if (land != null) { // If land found, use parcel uuid from here because the value from SP will be blank if the avatar hasnt moved landParcelName = land.LandData.Name; landParcelID = land.LandData.GlobalID; } else { m_log.WarnFormat( "[PROFILES]: PickInfoUpdate found no parcel info at {0},{1} in {2}", avaPos.X, avaPos.Y, p.Scene.Name); } pick.PickId = pickID; pick.CreatorId = creatorID; pick.TopPick = topPick; pick.Name = name; pick.Desc = desc; pick.ParcelId = landParcelID; pick.SnapshotId = snapshotID; pick.ParcelName = landParcelName; pick.SimName = remoteClient.Scene.RegionInfo.RegionName; pick.Gatekeeper = MyGatekeeper; pick.GlobalPos = posGlobal.ToString(); pick.SortOrder = sortOrder; pick.Enabled = enabled; object Pick = (object)pick; if (!rpc.JsonRpcRequest(ref Pick, "picks_update", serverURI, UUID.Random().ToString())) { remoteClient.SendAgentAlertMessage( "Error updating pick", false); return; } m_log.DebugFormat("[PROFILES]: Finish PickInfoUpdate {0} {1}", pick.Name, pick.PickId.ToString()); }
public override string ToString() { return(position.ToString()); }
public override string ToString() { return(position.ToString("F2") + "\n" + rotation.ToString("F2") + "\n" + scale.ToString("F2")); }
/// <summary> /// This deals with saving the report into the database. /// </summary> /// <param name="client"></param> /// <param name="regionName"></param> /// <param name="abuserID"></param> /// <param name="catagory"></param> /// <param name="checkflags"></param> /// <param name="details"></param> /// <param name="objectID"></param> /// <param name="position"></param> /// <param name="reportType"></param> /// <param name="screenshotID"></param> /// <param name="summery"></param> /// <param name="reporter"></param> private void UserReport(IClientAPI client, string regionName, UUID abuserID, byte catagory, byte checkflags, string details, UUID objectID, Vector3 position, byte reportType, UUID screenshotID, string summery, UUID reporter) { AbuseReport report = new AbuseReport { ObjectUUID = objectID, ObjectPosition = position.ToString(), Active = true, Checked = false, Notes = "", AssignedTo = "No One", ScreenshotID = screenshotID }; if (objectID != UUID.Zero) { ISceneChildEntity Object = client.Scene.GetSceneObjectPart(objectID); report.ObjectName = Object.Name; } else { report.ObjectName = ""; } string[] detailssplit = details.Split('\n'); string AbuseDetails = detailssplit[detailssplit.Length - 1]; report.AbuseDetails = AbuseDetails; report.ReporterName = client.Name; string[] findRegion = summery.Split('|'); report.RegionName = findRegion[1]; string[] findLocation = summery.Split('('); string[] findLocationend = findLocation[1].Split(')'); report.AbuseLocation = findLocationend[0]; string[] findCategory = summery.Split('['); string[] findCategoryend = findCategory[1].Split(']'); report.Category = findCategoryend[0]; string[] findAbuserName = summery.Split('{'); string[] findAbuserNameend = findAbuserName[1].Split('}'); report.AbuserName = findAbuserNameend[0]; string[] findSummary = summery.Split('\"'); string abuseSummary = findSummary[1]; if (findSummary.Length != 0) { abuseSummary = findSummary[1]; } report.AbuseSummary = abuseSummary; report.Number = (-1); EstateSettings ES = client.Scene.RegionInfo.EstateSettings; //If the abuse email is set up and the email module is available, send the email if (ES.AbuseEmailToEstateOwner && ES.AbuseEmail != "") { IEmailModule Email = m_Scene.RequestModuleInterface <IEmailModule>(); if (Email != null) { Email.SendEmail(UUID.Zero, ES.AbuseEmail, "Abuse Report", "This abuse report was submitted by " + report.ReporterName + " against " + report.AbuserName + " at " + report.AbuseLocation + " in your region " + report.RegionName + ". Summary: " + report.AbuseSummary + ". Details: " + report.AbuseDetails + ".", client.Scene); } } //Tell the DB about it IAbuseReports conn = m_Scene.RequestModuleInterface <IAbuseReports>(); if (conn != null) { conn.AddAbuseReport(report); } }
// Use this for initialization void Start() { //numberOfParticles = heightMap.width * heightMap.height / 64; //Makes the texture readable: https://forum.unity.com/threads/help-on-setting-read-write-enabled-flag-on-texture.211235/ /*string path = AssetDatabase.GetAssetPath(heightMap); * TextureImporter A = (TextureImporter)AssetImporter.GetAtPath(path); * A.isReadable = true; * AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);*/ heightMap = rotateTexture(heightMap, true); heightMap = rotateTexture(heightMap, true); b = heightMappedObject.GetComponent <Renderer>().bounds; heightMapBottomLeft = new Vector3(b.center.x - b.extents.x, 0f, b.center.z - b.extents.z); heightMapBottomRight = new Vector3(b.center.x + b.extents.x, 0f, b.center.z - b.extents.z); heightMapUpperLeft = new Vector3(b.center.x - b.extents.x, 0f, b.center.z + b.extents.z); heightMapUpperRight = new Vector3(b.center.x + b.extents.x, 0f, b.center.z + b.extents.z); Debug.Log("Bottom Left: " + heightMapBottomLeft.ToString()); Debug.Log("Bottom Right: " + heightMapBottomRight.ToString()); Debug.Log("Top Left: " + heightMapUpperLeft.ToString()); Debug.Log("Top Right: " + heightMapUpperRight.ToString()); mesh = new Mesh(); GetComponent <MeshFilter>().mesh = mesh; particleBuffer = new ComputeBuffer(numberOfParticles, System.Runtime.InteropServices.Marshal.SizeOf(typeof(Particle))); Particle[] particleArray = new Particle[numberOfParticles]; output = new Particle[numberOfParticles]; for (int i = 0; i < numberOfParticles; ++i) { particleArray[i].position.x = UnityEngine.Random.Range((float)(heightMapBottomLeft.x), (float)(heightMapBottomRight.x)); particleArray[i].position.y = 6f; particleArray[i].position.z = UnityEngine.Random.Range((float)(heightMapBottomLeft.z), (float)(heightMapUpperLeft.z)); particleArray[i].position.w = 1; particleArray[i].velocity.x = UnityEngine.Random.Range(.01f, .1f); particleArray[i].velocity.y = .01f; particleArray[i].velocity.z = UnityEngine.Random.Range(.01f, .1f); particleArray[i].velocity.w = 0; } particleBuffer.SetData(particleArray); kernelID = compute.FindKernel("CSMain"); compute.SetBuffer(kernelID, "particleBuffer", particleBuffer); CreateMesh(particleArray); compute.SetTexture(kernelID, "HeightMapTexture", heightMap); heightMappedObject.transform.position = new Vector3(heightMappedObject.transform.position.x + 6f, heightMappedObject.transform.position.y, heightMappedObject.transform.position.z - 10f); /*colorBuffer = new ComputeBuffer(heightMap.width * heightMap.height, sizeof(float) * 4); * Color[] colorData = heightMap.GetPixels(0); * colorBuffer.SetData(colorData); * compute.SetBuffer(kernelID, "heightMap", colorBuffer);*/ /*for (int i = 0; i < colorData.Length;) { * Debug.Log(colorData[i]); * i += 1000; * }*///This piece shows that the data we're reading is indeed a black and white image since R=G=B }
public void Update() { if (Input.GetKeyDown(KeyCode.F11)) { _visible = !_visible; var cg = OverlayCanvas.GetComponent <CanvasGroup>(); StartCoroutine(_visible ? CanvasUtil.FadeInCanvasGroup(cg) : CanvasUtil.FadeOutCanvasGroup(cg)); } textComp.text = ""; if (!_enabled || !_visible || PlayerMachine == null) { return; } if (Input.GetKeyDown(KeyCode.F1) || Input.GetKeyDown(KeyCode.Keypad1)) { bool?a = PlayerMachine.CoyoteFrameEnabled; PlayerMachine.CoyoteFrameEnabled = a.HasValue ? (a.Value ? false : new bool?()) : true; } if (Input.GetKeyDown(KeyCode.LeftBracket)) { if (--currentCostIdx < 0) { currentCostIdx = costumeNames.Length - 1; } } else if (Input.GetKeyDown(KeyCode.RightBracket)) { currentCostIdx = (currentCostIdx + 1) % (costumeNames.Length); } else if (Input.GetKeyDown(KeyCode.F2) || Input.GetKeyDown(KeyCode.Keypad2)) { PlayerMachine.SetCostume((Costumes)currentCostIdx); GameObject.FindGameObjectWithTag("Manager").GetComponent <DialogueSystem>().UpdateCostumePortrait(); } if (dialogueCache.Count > 0) { if (Input.GetKeyDown(KeyCode.Comma)) { if (--currentNpcIdx < 0) { currentNpcIdx = dialogueCache.Count - 1; } } else if (Input.GetKeyDown(KeyCode.Period)) { currentNpcIdx = (currentNpcIdx + 1) % dialogueCache.Count; } else if (Input.GetKeyDown(KeyCode.F3)) { GameObject.FindGameObjectWithTag("Manager").GetComponent <DialogueSystem>().Begin(dialogueCache[currentNpcIdx].TextAsset, null); } } if (Input.GetKeyDown(KeyCode.F4) || Input.GetKeyDown(KeyCode.Keypad4)) { if (Time.timeScale > 0) { float timeScale = Time.timeScale / 2; if (timeScale < 0.25f) { timeScale = 2.0f; } Time.timeScale = timeScale; } } if ((Input.GetKeyDown(KeyCode.F5) || Input.GetKeyDown(KeyCode.Keypad5) || Input.GetMouseButtonDown(4)) && !PlayerMachine.currentState.Equals(PlayerStates.Loading)) { PlayerMachine.EndScene(); } if (Input.GetKeyDown(KeyCode.F6) || Input.GetKeyDown(KeyCode.Keypad6)) { ++QualitySettings.vSyncCount; QualitySettings.vSyncCount %= 3; } bool inVoid = SceneManager.GetActiveScene().name == "void"; if ((Input.GetKeyDown(KeyCode.F7) || Input.GetKeyDown(KeyCode.Keypad7)) && !PlayerMachine.currentState.Equals(PlayerStates.Loading)) { var pizza = FindObjectOfType <PizzaBox>(); if (pizza == null) { Logger.LogError("No PizzaBox!"); } else { string level = (!inVoid) ? "void" : levelNames[currentLvlIdx]; deathPlaneStatus = true; GameObject.Find("Global Manager").GetComponent <Manager>().LoadScene(level, pizza.ExitId, pizza.gameObject); } } else if (inVoid && Input.GetKeyDown(KeyCode.L)) { do { currentLvlIdx = (currentLvlIdx + 1) % levelNames.Length; } while (levelNames[currentLvlIdx] == SceneManager.GetActiveScene().name); } if (!inVoid && Input.GetKeyDown(KeyCode.K)) { var key = FindObjectsOfType <Key>(); foreach (var k in key) { if (!k.pickedUp) { k.transform.position = PlayerMachine.gameObject.transform.position; } } } if (Input.GetKeyDown(KeyCode.G)) { talkVolumeRenderFlag = !talkVolumeRenderFlag; if (talkVolumeRenderFlag) { tvRadiusCache.UpdateCache(TalkVolumeCreator, talkVolumeRenderFlag); } else { tvRadiusCache.ToggleAllObjects(talkVolumeRenderFlag); } } if (Input.GetKeyDown(KeyCode.T) && !PlayerMachine.currentState.Equals(PlayerStates.Loading)) { SetupNoClip(!NoClipActive); } if (Input.GetKeyDown(KeyCode.M)) { var deathPlanes = FindObjectsOfType <VoidOut>(); deathPlaneStatus = !deathPlaneStatus; foreach (var d in deathPlanes) { d.setActive(deathPlaneStatus); } } else if (Input.GetKeyDown(KeyCode.V)) { collisionRenderFlag = !collisionRenderFlag; if (collisionRenderFlag) { collPlaneCache.UpdateCache(VoidOutCreator, collisionRenderFlag); } else { collPlaneCache.ToggleAllObjects(collisionRenderFlag); } } if ((Input.GetMouseButtonDown(3) || Input.GetKeyDown(KeyCode.R)) && (PlayerMachine.currentState.Equals(PlayerStates.Jump) || PlayerMachine.currentState.Equals(PlayerStates.Loading)) && warpCam.enabled) { MoveWarpCam(); yaw = warpCam.transform.eulerAngles.y; pitch = warpCam.transform.eulerAngles.x; } else if (Input.GetMouseButton(2)) { yaw += Input.GetAxis("Mouse X") * 2f; pitch -= Input.GetAxis("Mouse Y") * 2f; warpCam.transform.eulerAngles = new Vector3(pitch, yaw, 0f); } else if (Input.GetKeyDown(KeyCode.B)) { warpCam.enabled = !warpCam.enabled; } if (Input.GetKeyDown(KeyCode.N) && modTextures.ContainsKey("glass")) { if (Physics.Raycast( PlayerMachine.transform.position + PlayerMachine.controller.up * PlayerMachine.controller.height * 0.85f, PlayerMachine.lookDirection, out RaycastHit objHit)) { Logger.LogFine($"Hit an object: {objHit.collider.gameObject.name}"); var renderer = objHit.collider.gameObject.GetComponent <Renderer>(); var shader = Shader.Find("psx/trasparent/vertexlit"); if (renderer && shader) { for (int i = 0; i < renderer.materials.Length; ++i) { var matl = renderer.materials[i]; matl.shader = shader; matl.SetTexture("_MainTex", modTextures["glass"]); matl.SetColor("_Color", Color.blue); renderer.materials[i] = matl; } GameObject go = new GameObject(); Vector3 start = PlayerMachine.transform.position + PlayerMachine.controller.up * PlayerMachine.controller.height * 0.85f; go.transform.position = start; var lineRenderer = go.AddComponent <LineRenderer>(); lineRenderer.material = new Material(Shader.Find("Standard")); lineRenderer.material.SetColor("_Color", Color.red); lineRenderer.startColor = Color.red; lineRenderer.endColor = Color.red; lineRenderer.startWidth = 0.1f; lineRenderer.SetPosition(0, start); lineRenderer.SetPosition(1, objHit.point); Destroy(go, 0.3f); } } } if (Input.GetKeyDown(KeyCode.F8) || Input.GetKeyDown(KeyCode.Keypad8)) { CamEventReset = !CamEventReset; } deltaTime += (Time.unscaledDeltaTime - deltaTime) * 0.1f; bool?b = PlayerMachine.CoyoteFrameEnabled; textBuilder.Length = 0; textBuilder.AppendFormat("FPS: {0:F3}\n", 1f / deltaTime); textBuilder.AppendFormat("<F1>: Coyote Frames: {0}\n", b.HasValue ? OnOffStr(b.Value) : "Default"); textBuilder.Append("<F2><[]>: Set Costume: ").AppendLine(costumeNames[currentCostIdx]); if (dialogueCache.Count > 0) { textBuilder.AppendFormat("<F3><,.>: Dialogue: ").AppendLine(dialogueCache[currentNpcIdx].NpcName); } textBuilder.Append("<F4>: Time Scale: x").AppendLine(Time.timeScale.ToString("F2")); textBuilder.Append("<F5>: Text Storage/Warp\n"); textBuilder.AppendFormat("<F6>: VSync Count :{0}\n", QualitySettings.vSyncCount); textBuilder.AppendFormat("<F7><L>: Level Load: {0}\n", !inVoid ? "void" : levelNames[currentLvlIdx]); if (camEventsFound) { textBuilder.AppendFormat("<F8>: Repeat Cam Events: {0}\n", OnOffStr(CamEventReset)); } textBuilder.Append("<V>: Render Death Planes: ").AppendLine(OnOffStr(collisionRenderFlag)); textBuilder.Append("<M>: Active Death Planes: ").AppendLine(OnOffStr(deathPlaneStatus)); textBuilder.Append("<G>: Show NPC Talk Zone: ").AppendLine(OnOffStr(talkVolumeRenderFlag)); textBuilder.Append("<K>: Get All Keys\n"); textBuilder.Append("<R><noparse><B></noparse>: Warp Cam Move/Toggle\n"); textBuilder.Append("<N>: Set Obj Transparent\n"); textBuilder.Append("<T>: NoClip: ").AppendLine(OnOffStr(NoClipActive)); textBuilder.Append("<F11> Toggle UI\n").AppendLine(); textBuilder.Append("Move Dir:").AppendLine(PlayerMachine.moveDirection.ToString()); textBuilder.Append("Pos:").AppendLine(PlayerMachine.transform.position.ToString()); textBuilder.Append("SpawnPos:").AppendLine(PlayerMachine.LastGroundLoc.ToString()); textBuilder.Append("Look Dir:").AppendLine(PlayerMachine.lookDirection.ToString()); textBuilder.Append("Player State:").AppendLine(PlayerMachine.currentState.ToString()); if (bossController) { textBuilder.AppendLine(); textBuilder.Append("Boss Health: ").AppendLine(bossController.Health.ToString()); textBuilder.Append("Boss State: ").AppendLine(bossStates[(int)BossController.State]); } if (warpCam.enabled) { textBuilder.AppendLine(); textBuilder.Append("LGP:").AppendLine(PlayerMachine.controller.LastGroundPos.ToString()); textBuilder.Append("LGO:").AppendLine(PlayerMachine.controller.LastGroundOffset.ToString()); textBuilder.Append("LGR:").AppendLine(PlayerMachine.controller.LastGroundRot.ToString()); textBuilder.Append("CG:").AppendLine(PlayerMachine.controller.currentGround.transform.position.ToString()); textBuilder.Append("CR:").AppendLine(PlayerMachine.controller.currentGround.transform.rotation.ToString()); textBuilder.Append("Warp Pos:").AppendLine(warpSimPos.ToString()); } // Set text causes visual glitches textComp.text += textBuilder.ToString(); }
//Allow other scripts to spawn enemies at a location of their choosing public void RemoteSpawn(Vector3 _position) { if (m_enemyReady.Count == 0) { Debug.Log("Error: No entities remaining in pool\nSpawn requested from remote at: " + _position.ToString()); return; } GameObject obj = m_enemyReady.Pop(); obj.transform.parent = null; obj.transform.position = _position; obj.SetActive(true); obj.GetComponent <Enemy>().Init(); }
public override string ToString() { return(String.Format("({0}, {1})", translation.ToString(), rotation.ToString())); }
public override string ToString() { return("{Center:" + Center.ToString() + " Extents:" + HalfExtent.ToString() + " Orientation:" + Orientation.ToString() + "}"); }
private void Update() { isGrounded = checkGrounded(); GetComponent <Renderer>().material.color = myBallColour; GetComponent <TrailRenderer>().material.color = myBallColour; if (!isLocalPlayer) { return; } waitTime -= Time.deltaTime; if (Input.GetMouseButtonDown(0)) { if (canBeDirected && !isTakingShot) { isBeingDirected = true; } } if (isBeingDirected) { myShotForce += Input.GetAxis("Mouse Y") * shotForceMultiplier; myShotForce = Mathf.Clamp(myShotForce, 0, maxShotForce); powerMeter.SetActive(true); powerMeter.transform.GetChild(0).gameObject.GetComponent <Image>().fillAmount = (myShotForce / maxShotForce); } else { powerMeter.SetActive(false); myShotForce = 0; } if (Input.GetMouseButtonUp(0)) { if (isBeingDirected && canBeDirected && !isTakingShot && myShotForce >= 0) { waitTime = minimumShotTime; isTakingShot = true; CmdUpdateBall(); CmdTakeShot(myCamController.axis1.transform.up * myShotForce); myShotForce = 0; } isBeingDirected = false; } if (Input.GetButtonDown("Jump") && isTakingShot && checkGrounded()) { CmdUpdateBall(); CmdJumpBall(); } if (isTakingShot && GetComponent <Rigidbody>().velocity.magnitude <= velocityStopPoint && waitTime <= 0 && checkGrounded()) { isTakingShot = false; CmdStopMovement(); CmdEndShot(); } myCamController.isGrounded = checkGrounded(); GameObject.Find("Gravity Vector UI Text").GetComponent <Text>().text = "Gravity Vector : " + gravityUpVectorNormalised.ToString(); GameObject.Find("Moving UI Text").GetComponent <Text>().text = "Moving : " + isTakingShot.ToString(); GameObject.Find("Grounded UI Text").GetComponent <Text>().text = "Grounded : " + isGrounded.ToString(); if (GameObject.Find("Color Selector Panel")) { myBallColour = GameObject.Find("Color Selector Panel").GetComponent <ColourSelector_Script>().resultColor; CmdSetBallColor(myBallColour); } if (isGrounded) { GetComponent <Rigidbody>().angularDrag = 0.2f; } else { GetComponent <Rigidbody>().angularDrag = 0f; } }
public override string ToString() { return($"{ColorMask.ToString()}/{Skin.String}"); }
protected void InternalUpdatePosition() { try { HkRigidBody havokBody = PhysicsBody; if (havokBody == null) { return; } Vector3 newPosition = m_positionOrientation.Position; if (SandboxGameAssemblyWrapper.IsDebugging) { LogManager.APILog.WriteLineAndConsole(this.GetType().Name + " - Changing position of '" + Name + "' from '" + havokBody.Position.ToString() + "' to '" + newPosition.ToString() + "'"); } havokBody.Position = newPosition; } catch (Exception ex) { LogManager.ErrorLog.WriteLine(ex); } }
public static string VectorFunction(Vector3 value) { // TODO return("VECTOR3( " + Coma + value.ToString() + Coma + " )"); }
public override string ToString() { return("N:" + number + "|| L:" + Location.ToString() + "|| R:" + Rot.ToString()); }
public string ToString(string format) { return(string.Format("Circle3(center: {0}, normal: {1}, radius: {2})", center.ToString(format), normal.ToString(format), radius.ToString(format))); }
IEnumerator timeBasedTesting() { yield return(new WaitForEndOfFrame()); GameObject cubeNormal = cubeNamed("normalTimeScale"); // float timeElapsedNormal = Time.time; LeanTween.moveX(cubeNormal, 12f, 1.5f).setIgnoreTimeScale(false).setOnComplete(() => { timeElapsedNormalTimeScale = Time.time; }); LTDescr[] descr = LeanTween.descriptions(cubeNormal); LeanTest.expect(descr.Length >= 0 && descr[0].to.x == 12f, "WE CAN RETRIEVE A DESCRIPTION"); GameObject cubeIgnore = cubeNamed("ignoreTimeScale"); LeanTween.moveX(cubeIgnore, 5f, 1.5f).setIgnoreTimeScale(true).setOnComplete(() => { timeElapsedIgnoreTimeScale = Time.time; }); yield return(new WaitForSeconds(1.5f)); LeanTest.expect(Mathf.Abs(timeElapsedNormalTimeScale - timeElapsedIgnoreTimeScale) < 0.7f, "START IGNORE TIMING", "timeElapsedIgnoreTimeScale:" + timeElapsedIgnoreTimeScale + " timeElapsedNormalTimeScale:" + timeElapsedNormalTimeScale); // yield return new WaitForSeconds(100f); Time.timeScale = 4f; int pauseCount = 0; LeanTween.value(gameObject, 0f, 1f, 1f).setOnUpdate(( float val ) => { pauseCount++; }).pause(); // Bezier should end at exact end position not just 99% close to it Vector3[] roundCirc = new Vector3[] { new Vector3(0f, 0f, 0f), new Vector3(-9.1f, 25.1f, 0f), new Vector3(-1.2f, 15.9f, 0f), new Vector3(-25f, 25f, 0f), new Vector3(-25f, 25f, 0f), new Vector3(-50.1f, 15.9f, 0f), new Vector3(-40.9f, 25.1f, 0f), new Vector3(-50f, 0f, 0f), new Vector3(-50f, 0f, 0f), new Vector3(-40.9f, -25.1f, 0f), new Vector3(-50.1f, -15.9f, 0f), new Vector3(-25f, -25f, 0f), new Vector3(-25f, -25f, 0f), new Vector3(0f, -15.9f, 0f), new Vector3(-9.1f, -25.1f, 0f), new Vector3(0f, 0f, 0f) }; GameObject cubeRound = cubeNamed("bRound"); Vector3 onStartPos = cubeRound.transform.position; LeanTween.moveLocal(cubeRound, roundCirc, 0.5f).setOnComplete(() => { LeanTest.expect(cubeRound.transform.position == onStartPos, "BEZIER CLOSED LOOP SHOULD END AT START", "onStartPos:" + onStartPos + " onEnd:" + cubeRound.transform.position); }); // should be able to retrieve a point LTBezierPath roundCircPath = new LTBezierPath(roundCirc); float ratioPoint = roundCircPath.ratioAtPoint(new Vector3(-25f, 25f, 0f)); LeanTest.expect(Mathf.Equals(ratioPoint, 0.25f), "BEZIER RATIO POINT"); // Spline should end at exact end position not just 99% close to it Vector3[] roundSpline = new Vector3[] { new Vector3(0f, 0f, 0f), new Vector3(0f, 0f, 0f), new Vector3(2f, 0f, 0f), new Vector3(0.9f, 2f, 0f), new Vector3(0f, 0f, 0f), new Vector3(0f, 0f, 0f) }; GameObject cubeSpline = cubeNamed("bSpline"); Vector3 onStartPosSpline = cubeSpline.transform.position; LeanTween.moveSplineLocal(cubeSpline, roundSpline, 0.5f).setOnComplete(() => { LeanTest.expect(Vector3.Distance(onStartPosSpline, cubeSpline.transform.position) <= 0.01f, "SPLINE CLOSED LOOP SHOULD END AT START", "onStartPos:" + onStartPosSpline + " onEnd:" + cubeSpline.transform.position + " dist:" + Vector3.Distance(onStartPosSpline, cubeSpline.transform.position)); }); // Sequence test, do three tweens and make sure they end at the right points GameObject cubeSeq = cubeNamed("cSeq"); var seq = LeanTween.sequence().append(LeanTween.moveX(cubeSeq, 100f, 0.2f)); seq.append(0.1f).append(LeanTween.scaleX(cubeSeq, 2f, 0.1f)); seq.append(() => { LeanTest.expect(cubeSeq.transform.position.x == 100f, "SEQ MOVE X FINISHED", "move x:" + cubeSeq.transform.position.x); LeanTest.expect(cubeSeq.transform.localScale.x == 2f, "SEQ SCALE X FINISHED", "scale x:" + cubeSeq.transform.localScale.x); }).setScale(0.2f); // Bounds check GameObject cubeBounds = cubeNamed("cBounds"); bool didPassBounds = true; Vector3 failPoint = Vector3.zero; LeanTween.move(cubeBounds, new Vector3(10, 10, 10), 0.1f).setOnUpdate((float val) => { // Debug.LogWarning("cubeBounds x:"+cubeBounds.transform.position.x + " y:"+ cubeBounds.transform.position.y+" z:"+cubeBounds.transform.position.z); if (cubeBounds.transform.position.x < 0f || cubeBounds.transform.position.x > 10f || cubeBounds.transform.position.y < 0f || cubeBounds.transform.position.y > 10f || cubeBounds.transform.position.z < 0f || cubeBounds.transform.position.z > 10f) { didPassBounds = false; failPoint = cubeBounds.transform.position; // Debug.LogError("OUT OF BOUNDS"); } }).setLoopPingPong().setRepeat(8).setOnComplete(() => { LeanTest.expect(didPassBounds, "OUT OF BOUNDS", "pos x:" + failPoint.x + " y:" + failPoint.y + " z:" + failPoint.z); }); // Local scale check //GameObject cubeLocal = cubeNamed("cLocal"); //LeanTween.scale(cubeLocal, new Vector3(0.5f, 0.5f, 0.5f), 0.2f).setOnComplete(() => //{ // LeanTest.expect((cubeLocal.transform.localScale.x == 0.5f && cubeLocal.transform.localScale.y == 0.5f && cubeLocal.transform.localScale.z == 0.5f), "SCALE WORKS", "scale x:" + cubeLocal.transform.localScale.x + " y:" + cubeLocal.transform.localScale.y + " z:" + cubeLocal.transform.localScale.z); //}); // Groups of tweens testing groupTweens = new LTDescr[1200]; groupGOs = new GameObject[groupTweens.Length]; groupTweensCnt = 0; int descriptionMatchCount = 0; for (int i = 0; i < groupTweens.Length; i++) { GameObject cube = cubeNamed("c" + i); cube.transform.position = new Vector3(0, 0, i * 3); groupGOs[i] = cube; } yield return(new WaitForEndOfFrame()); bool hasGroupTweensCheckStarted = false; int setOnStartNum = 0; int setPosNum = 0; bool setPosOnUpdate = true; for (int i = 0; i < groupTweens.Length; i++) { Vector3 finalPos = transform.position + Vector3.one * 3f; Dictionary <string, object> finalDict = new Dictionary <string, object> { { "final", finalPos }, { "go", groupGOs[i] } }; groupTweens[i] = LeanTween.move(groupGOs[i], finalPos, 3f).setOnStart(() => { setOnStartNum++; }).setOnUpdate((Vector3 newPosition) => { if (transform.position.z > newPosition.z) { setPosOnUpdate = false; } // Debug.LogWarning("New Position: " + newPosition.ToString()); }). setOnCompleteParam(finalDict). setOnComplete((object param) => { Dictionary <string, object> finalDictRetr = param as Dictionary <string, object>; Vector3 neededPos = (Vector3)finalDictRetr["final"]; GameObject tweenedGo = finalDictRetr["go"] as GameObject; if (neededPos.ToString() == tweenedGo.transform.position.ToString()) { setPosNum++; } else { // Debug.Log("neededPos:"+neededPos+" tweenedGo.transform.position:"+tweenedGo.transform.position); } if (hasGroupTweensCheckStarted == false) { hasGroupTweensCheckStarted = true; LeanTween.delayedCall(gameObject, 0.1f, () => { LeanTest.expect(setOnStartNum == groupTweens.Length, "SETONSTART CALLS", "expected:" + groupTweens.Length + " was:" + setOnStartNum); LeanTest.expect(groupTweensCnt == groupTweens.Length, "GROUP FINISH", "expected " + groupTweens.Length + " tweens but got " + groupTweensCnt); LeanTest.expect(setPosNum == groupTweens.Length, "GROUP POSITION FINISH", "expected " + groupTweens.Length + " tweens but got " + setPosNum); LeanTest.expect(setPosOnUpdate, "GROUP POSITION ON UPDATE"); }); } groupTweensCnt++; }); if (LeanTween.description(groupTweens[i].id).trans == groupTweens[i].trans) { descriptionMatchCount++; } } while (LeanTween.tweensRunning < groupTweens.Length) { yield return(null); } LeanTest.expect(descriptionMatchCount == groupTweens.Length, "GROUP IDS MATCH"); int expectedSearch = groupTweens.Length + 7; LeanTest.expect(LeanTween.maxSearch <= expectedSearch, "MAX SEARCH OPTIMIZED", "maxSearch:" + LeanTween.maxSearch + " should be:" + expectedSearch); LeanTest.expect(LeanTween.isTweening() == true, "SOMETHING IS TWEENING"); // resume item before calling pause should continue item along it's way float previousXlt4 = cube4.transform.position.x; lt4 = LeanTween.moveX(cube4, 5.0f, 1.1f).setOnComplete(() => { LeanTest.expect(cube4 != null && previousXlt4 != cube4.transform.position.x, "RESUME OUT OF ORDER", "cube4:" + cube4 + " previousXlt4:" + previousXlt4 + " cube4.transform.position.x:" + (cube4 != null ? cube4.transform.position.x : 0)); }).setDestroyOnComplete(true); lt4.resume(); rotateRepeat = rotateRepeatAngle = 0; LeanTween.rotateAround(cube3, Vector3.forward, 360f, 0.1f).setRepeat(3).setOnComplete(rotateRepeatFinished).setOnCompleteOnRepeat(true).setDestroyOnComplete(true); yield return(new WaitForEndOfFrame()); LeanTween.delayedCall(0.1f * 8f + 1f, rotateRepeatAllFinished); int countBeforeCancel = LeanTween.tweensRunning; LeanTween.cancel(lt1Id); LeanTest.expect(countBeforeCancel == LeanTween.tweensRunning, "CANCEL AFTER RESET SHOULD FAIL", "expected " + countBeforeCancel + " but got " + LeanTween.tweensRunning); LeanTween.cancel(cube2); int tweenCount = 0; for (int i = 0; i < groupTweens.Length; i++) { if (LeanTween.isTweening(groupGOs[i])) { tweenCount++; } if (i % 3 == 0) { LeanTween.pause(groupGOs[i]); } else if (i % 3 == 1) { groupTweens[i].pause(); } else { LeanTween.pause(groupTweens[i].id); } } LeanTest.expect(tweenCount == groupTweens.Length, "GROUP ISTWEENING", "expected " + groupTweens.Length + " tweens but got " + tweenCount); yield return(new WaitForEndOfFrame()); tweenCount = 0; for (int i = 0; i < groupTweens.Length; i++) { if (i % 3 == 0) { LeanTween.resume(groupGOs[i]); } else if (i % 3 == 1) { groupTweens[i].resume(); } else { LeanTween.resume(groupTweens[i].id); } if (i % 2 == 0 ? LeanTween.isTweening(groupTweens[i].id) : LeanTween.isTweening(groupGOs[i])) { tweenCount++; } } LeanTest.expect(tweenCount == groupTweens.Length, "GROUP RESUME"); LeanTest.expect(LeanTween.isTweening(cube1) == false, "CANCEL TWEEN LTDESCR"); LeanTest.expect(LeanTween.isTweening(cube2) == false, "CANCEL TWEEN LEANTWEEN"); LeanTest.expect(pauseCount == 0, "ON UPDATE NOT CALLED DURING PAUSE", "expect pause count of 0, but got " + pauseCount); yield return(new WaitForEndOfFrame()); Time.timeScale = 0.25f; float tweenTime = 0.2f; float expectedTime = tweenTime * (1f / Time.timeScale); float start = Time.realtimeSinceStartup; bool onUpdateWasCalled = false; LeanTween.moveX(cube1, -5f, tweenTime).setOnUpdate((float val) => { onUpdateWasCalled = true; }).setOnComplete(() => { float end = Time.realtimeSinceStartup; float diff = end - start; LeanTest.expect(Mathf.Abs(expectedTime - diff) < 0.06f, "SCALED TIMING DIFFERENCE", "expected to complete in roughly " + expectedTime + " but completed in " + diff); LeanTest.expect(Mathf.Approximately(cube1.transform.position.x, -5f), "SCALED ENDING POSITION", "expected to end at -5f, but it ended at " + cube1.transform.position.x); LeanTest.expect(onUpdateWasCalled, "ON UPDATE FIRED"); }); bool didGetCorrectOnUpdate = false; LeanTween.value(gameObject, new Vector3(1f, 1f, 1f), new Vector3(10f, 10f, 10f), 1f).setOnUpdate(( Vector3 val ) => { didGetCorrectOnUpdate = val.x >= 1f && val.y >= 1f && val.z >= 1f; }).setOnComplete(() => { LeanTest.expect(didGetCorrectOnUpdate, "VECTOR3 CALLBACK CALLED"); }); yield return(new WaitForSeconds(expectedTime)); Time.timeScale = 1f; int ltCount = 0; GameObject[] allGos = FindObjectsOfType(typeof(GameObject)) as GameObject[]; foreach (GameObject go in allGos) { if (go.name == "~LeanTween") { ltCount++; } } LeanTest.expect(ltCount == 1, "RESET CORRECTLY CLEANS UP"); lotsOfCancels(); }