Mandelbrot Set function crashes - c#

i made a sim for the Mandelbrot Set function, zn + 1 = power(zn) + c
and it work but when i get to the point were the function is unstable it crashes, now i have a boolen that when true makes a wire that connects all the circles, when its false its fine(dosent crash) but when its on it does, the code works like this:
start:
building a list of circles and making there pos by the equation, and then crating a wire between the circle and the last circle,
update:
then when you move the circle it uses the already made list of gameobj to update there pos.
you can try it here:
build
github:
git
but it crashes:(, heres the code:
private void updateCircles()
{
StartUpdateCircles();
}
private void StartCircles()
{
float x = BlackCircle.anchoredPosition.x;
float y = BlackCircle.anchoredPosition.y;
AllCircles.Add(BlackCircle.gameObject);
for (int i = 1; i < itarations; i++)
{
Vector2 RedCircleVec2 = RedCircle.anchoredPosition;
Vector2 LastCircleVec2 = AllCircles[i - 1].GetComponent<RectTransform>().anchoredPosition;
GameObject Circle = Instantiate(BlackCircle.gameObject, Vector3.zero, Quaternion.identity);
Circle.transform.SetParent(CanvasPerent);
AllCircles.Add(Circle);
x = Mathf.Pow(x, 2);
x -= Mathf.Pow(LastCircleVec2.y, 2);
x += RedCircleVec2.x;
y = (2 * LastCircleVec2.x
* LastCircleVec2.y) + RedCircleVec2.y;
Circle.GetComponent<RectTransform>().anchoredPosition = new Vector2(x, y);
if (HasWire)
{
GameObject wire = GenrateWireStart(LastCircleVec2
, Circle.GetComponent<RectTransform>().anchoredPosition);
AllWires.Add(wire);
}
}
}
private void StartUpdateCircles()
{
float x = BlackCircle.anchoredPosition.x;
float y = BlackCircle.anchoredPosition.y;
for (int i = 1; i < itarations; i++)
{
Vector2 RedCircleVec2 = RedCircle.anchoredPosition;
Vector2 LastCircleVec2 = AllCircles[i - 1].GetComponent<RectTransform>().anchoredPosition;
RectTransform ICircle = AllCircles[i].GetComponent<RectTransform>();
x = Mathf.Pow(x, 2);
x -= Mathf.Pow(LastCircleVec2.y, 2);
x += RedCircleVec2.x;
y = (2 * LastCircleVec2.x
* LastCircleVec2.y) + RedCircleVec2.y;
ICircle.anchoredPosition = new Vector2(x, y);
if (HasWire)
{
GenrateWireUpdate(LastCircleVec2
,ICircle.anchoredPosition, i);
}
}
}
public GameObject GenrateWireStart(Vector2 NodeA, Vector2 NodeB)
{
GameObject Connector = new GameObject("connector", typeof(Image));
Connector.transform.SetParent(CanvasPerent);
RectTransform ConnectorRT = Connector.GetComponent<RectTransform>();
ConnectorRT.anchorMin = new Vector2(0, 0);
ConnectorRT.anchorMax = new Vector2(0, 0);
Connector.GetComponent<Image>().color = new Color(0f, 0f, 0f, 0.25f);
Vector2 dir = (NodeB - NodeA).normalized;
float distance = Vector2.Distance(NodeA, NodeB);
ConnectorRT.sizeDelta = new Vector2(distance, 0.005f);
ConnectorRT.position = NodeA + dir * distance * .5f;
ConnectorRT.localEulerAngles = new Vector3(0, 0, UtilsClass.GetAngleFromVectorFloat(dir));
return Connector;
}
public void GenrateWireUpdate(Vector2 NodeA, Vector2 NodeB, int i)
{
RectTransform ConnectorRT = AllWires[i - 1].GetComponent<RectTransform>();
Vector2 dir = (NodeB - NodeA).normalized;
float distance = Vector2.Distance(NodeA, NodeB);
ConnectorRT.sizeDelta = new Vector2(distance, 0.005f);
ConnectorRT.position = NodeA + dir * distance * .5f;
ConnectorRT.localEulerAngles = new Vector3(0, 0, UtilsClass.GetAngleFromVectorFloat(dir));
}
pls help, thank you.

I looked briefly into your code and you seem to get some invalid positions like infinite / undefined from your calculations or just some positions too far away for Unity.
I could remove these by simply limiting positions to e.g.
x = Mathf.Clamp(Mathf.Pow(x, 2), -Screen.width, Screen.width);
x = Mathf.Clamp(x - Mathf.Pow(LastCircleVec2.y, 2), -Screen.width, Screen.width);
x = Mathf.Clamp(x + RedCircleVec2.x, -Screen.width, Screen.width);
y = Mathf.Clamp((2 * LastCircleVec2.x * LastCircleVec2.y) + RedCircleVec2.y, -Screen.width, Screen.width);
which simply limits all positions to some off-screen max positions

Related

Newbie cant generate a chessboard in Godot 3

I'm new to godot 3.4! My first project is a orthographic chess make. I cant generate the chess board.
I've wrote the following script trying to generate the chessboard:
using Godot;
using System;
public class TileSpawner : Spatial {
[Export] private readonly Material lightSquare;
[Export] private readonly Material darkSquare;
private bool isLight = false;
public override void _Ready() {
Vector2 coordinates = new Vector2(0, 0);
for (int y = 0; y < 8; y++)
for (int x = 0; x < 8; x++) {
coordinates.x = x; coordinates.y = y;
AddChild(MakeTile(coordinates));
}
}
private MeshInstance MakeTile(Vector2 coordinates) {
MeshInstance mesh = new MeshInstance() {
Mesh = new CubeMesh() {
Material = isLight ? lightSquare : darkSquare
}
};
mesh.Translate(new Vector3(-coordinates.x, 0, coordinates.y) + new Vector3(coordinates.x/2, 0, -coordinates.y/2));
mesh.Scale = new Vector3(1.0f, 0.2f, 1.0f);
isLight = !isLight;
return mesh;
}
}
and the result its flickery...
one object overlapping other
so I added this line on the MakeTile function to see the problem clearly:
mesh.Translate(isLight ? Vector3.Up : Vector3.Down);
and got something like this.there's two big block in place small 64 tiles
not sure what's going on. I've been trying to solve this for 4 hours.
#Theraot answer was promising but didn't changed any thing.
My Solution:
Step 1: Create a scene containing the dark and light square mesh.
Step 2: Go Scene(On the top left corner of the screen) > Convert To... > MeshLibrary.
Step 3: Tick the "Merge With Existing" Checkbox and save the file as name.meshlib
Step 4: Create a GridMap on the scene you want your chessboard to be in.
Step 5: Load the name.meshlib on the GridMap Node and attach the following script:
using Godot;
using System;
public class FillWithTile : GridMap {
public override void _Ready() {
Vector2 coordinates = new Vector2(0, 0);
for (int y = -4; y < 4; y++)
for (int x = -4; x < 4; x++) {
coordinates.x = x; coordinates.y = y;
MakeTile(coordinates);
}
}
private void MakeTile(Vector2 coordinates) {
SetCellItem((int)coordinates.x, 0, (int)coordinates.y, (coordinates.x % 2 == 0) != (coordinates.y % 2 == 0)?1:0);
}
}
We are going to make a Transform:
var t = new Transform(
x_axis,
y_axis,
z_axis,
origin
);
So, let us define the components we used there. First for origin I'm going to guess that leaving it zero is fine. You will be able to change it to move the board.
var origin = Vector3.Zero;
And I'm also assuming the axis can be in the usual directions, just scaled:
var x_axis = Vector3.Right;
var y_axis = Vector3.Up * 2.0f;
var z_axis = Vector3.Back;
Alternatively, do you want them rotated? You could do something like this:
var x_axis = (Vector3.Right + Vector3.Back).Normalized();
var y_axis = Vector3.Up * 2.0f;
var z_axis = (Vector3.Back + Vector3.Left).Normalized();
Addendum: The scale is too big. The tiles are taking up the area of four cells. So shrink on the x and z axis by half:
var x_axis = Vector3.Right * 0.5f;
var y_axis = Vector3.Up * 2.0f;
var z_axis = Vector3.Back * 0.5f;
Or for the other case:
var x_axis = (Vector3.Right + Vector3.Back).Normalized() * 0.5f;
var y_axis = Vector3.Up * 2.0f;
var z_axis = (Vector3.Back + Vector3.Left).Normalized() * 0.5f;
Now, do you remember I said this is the Transform?
var t = new Transform(
x_axis,
y_axis,
z_axis,
origin
);
Well, not quite. We are going to displace it according to the coordinates we got, like this:
var t = new Transform(
x_axis,
y_axis,
z_axis,
origin + x_axis * coordinates.x + z_axis * coordinates.y
);
Addendum: I think you need to compensate for halving the scale by doubling the offset here: origin + x_axis * coordinates.x * 2.0f + z_axis * coordinates.y * 2.0f
And set it to the mesh:
mesh.Transform = t;
Addendum: the decision of light vs dark si wrong. It goes by rows and switching, like this:
10101010
10101010
…
Here is an alternative algorithm:
isLight = (((int)coordinates.x) % 2 == 0) != (((int)coordinates.y) % 2 == 0)

Drawing a Mandelbrot Set

I'm trying to make the function of the Mandelbrot Set, and I'm not sure what I'm doing wrong or right, here's the code:
private void StartCircles()
{
float savePower = BlackCircle.anchoredPosition.x;
GameObject[] AllCircles = new GameObject[itarations];
AllCircles[0] = BlackCircle.gameObject;
for (int i = 1; i < itarations; i++)
{
GameObject Circle = Instantiate(BlackCircle.gameObject, Vector3.zero, Quaternion.identity);
Circle.transform.SetParent(CanvasPerent);
savePower = Mathf.Pow(savePower, 2);
savePower += RedCircle.anchoredPosition.x;
Circle.GetComponent<RectTransform>().anchoredPosition = new Vector2(savePower,
AllCircles[i - 1].GetComponent<RectTransform>().anchoredPosition.y * -1);
AllCircles[i] = Circle;
}
CleanSqud = new GameObject[itarations];
CleanSqud = AllCircles;
}
I'm not sure what the y position should be and how could the x position be < 0 if it's a power of 2, it's automaticly > 0.
Here's the display:
i manged to get my code working after some time and i got some answars to share if anyone has my problen:
well i only wanted to make the function of the zn + 1 = zn * zn + c
i dident made the full set only this function, heres my code:
#region Actions
private void OnDestroy()
{
MoveBlack.HasMoved -= HasMoved;
MoveBlack.HasStoped -= HasStoped;
MoveRed.HasMoved -= HasMoved;
MoveRed.HasStoped -= HasStoped;
}
private void LateUpdate()
{
if (moved) { updateCircles(); }
if (hasparty)
{
foreach(GameObject game in CleanSqud)
{
game.GetComponent<Image>().color = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f));
}
}
}
private void HasMoved()
{
moved = true;
}
private void HasStoped()
{
moved = false;
}
#endregion
#region Updateing
private void updateCircles()
{
foreach (GameObject Circle in CleanSqud) { if (Circle.gameObject.name != "BlackCirlce") { Destroy(Circle); } }
StartCircles();
}
private void StartCircles()
{
float x = BlackCircle.anchoredPosition.x;
float y = BlackCircle.anchoredPosition.y;
GameObject[] AllCircles = new GameObject[itarations];
AllCircles[0] = BlackCircle.gameObject;
for (int i = 1; i < itarations; i++)
{
GameObject Circle = Instantiate(BlackCircle.gameObject, Vector3.zero, Quaternion.identity);
Circle.transform.SetParent(CanvasPerent);
AllCircles[i] = Circle;
x = Mathf.Pow(x, 2);
x -= Mathf.Pow(AllCircles[i - 1].GetComponent<RectTransform>().anchoredPosition.y, 2);
x += RedCircle.anchoredPosition.x;
y = (2 * AllCircles[i - 1].GetComponent<RectTransform>().anchoredPosition.x
* AllCircles[i - 1].GetComponent<RectTransform>().anchoredPosition.y) + RedCircle.anchoredPosition.y;
Circle.GetComponent<RectTransform>().anchoredPosition = new Vector2(x, y);
}
CleanSqud = new GameObject[itarations];
CleanSqud = AllCircles;
}
#endregion
so what you should do is instad of showing the y as a imaginary and the x as real show it using the equastion:
this x = power of the old x - power of the old y + c.x
this y = 2 * the old x * the old y + c.y
this should work!
thanks.

Create a hexagonal grid where I can get the position of the corners

I find a lot of examples of creating a hex grid like the following. But I'm having a hard time understanding how I might have a list of the corners in a hex grid. Basically I'd want a character to move along the line of the grid instead of the center. so I want to grab the position of the next corner in the hex grid and move them there.
I was thinking of using a basic hex grid code to create the prefabs in the right place and then just add empty game objects on each corner of the prefab, but then I have a bunch of overlapping positions that are shared corners for each hexagon. I thought I could delete them if they are overlapping but it just all seems too brute force and hard to keep track of. I'd love to hear some ideas on approaching something like this. By the way I'd also want to know the center of the hex besides knowing the corners.
this code successfully creates a hex grid pattern where I can add a hex shaped game object to instance.
using UnityEngine;
public class Grid : MonoBehaviour
{
public Transform hexPrefab;
public int gridWidth = 11;
public int gridHeight = 11;
float hexWidth = 1.732f;
float hexHeight = 2.0f;
public float gap = 0.0f;
Vector3 startPos;
void Start()
{
AddGap();
CalcStartPos();
CreateGrid();
}
void AddGap()
{
hexWidth += hexWidth * gap;
hexHeight += hexHeight * gap;
}
void CalcStartPos()
{
float offset = 0;
if (gridHeight / 2 % 2 != 0)
offset = hexWidth / 2;
float x = -hexWidth * (gridWidth / 2) - offset;
float z = hexHeight * 0.75f * (gridHeight / 2);
startPos = new Vector3(x, 0, z);
}
Vector3 CalcWorldPos(Vector2 gridPos)
{
float offset = 0;
if (gridPos.y % 2 != 0)
offset = hexWidth / 2;
float x = startPos.x + gridPos.x * hexWidth + offset;
float z = startPos.z - gridPos.y * hexHeight * 0.75f;
return new Vector3(x, 0, z);
}
void CreateGrid()
{
for (int y = 0; y < gridHeight; y++)
{
for (int x = 0; x < gridWidth; x++)
{
Transform hex = Instantiate(hexPrefab) as Transform;
Vector2 gridPos = new Vector2(x, y);
hex.position = CalcWorldPos(gridPos);
hex.parent = this.transform;
hex.name = "Hexagon" + x + "|" + y;
}
}
}
}

How can I make a circle from grid of GameObjects?

What I am trying to achieve is something like this:
What I have so far is the edges for the circles.
I know this would involve a nested for loop. This is what I have so far:
public GameObject player;
private GameObject playerGrid;
public int numOfObjects;
private Vector3 centerPos;
public int size = 2;
public Vector2 speed = new Vector2(50, 50);
private float smoothTime = 0.25f;
void Start()
{
playerGrid = new GameObject();
centerPos = transform.position;
for (int i = 0; i < numOfObjects; i++)
{
float pointNum = (i * 1.0f) / numOfObjects;
float angle = pointNum * Mathf.PI * 2;
float r = size / 2 * (Mathf.PI);
float x = Mathf.Sin(angle) * r;
float y = Mathf.Cos(angle) * r;
Vector3 pointPos = new Vector3(x, y, 0) + centerPos;
GameObject obj = Instantiate(player, pointPos, Quaternion.identity);
obj.transform.SetParent(playerGrid.transform);
}
}
I am stuck on how to implement the conditional for the nested for loop. Also, I have trouble understanding the calculations of column positions in the nested for loop. I believe the conditional would be the start and end of I for that column or row: for(int j = i + 1; j < i - 1, j++)
For the col positions, I would think it would be incrementing the angle enough to give the square its space for that column: float x = (Mathf.Sin(angle) + somethingHere) * r;
I just not sure how to progress from here.
Here's a simple way to draw a circle:
public float circleRadius = 5f;
public float objectSize = 1f;
void OnDrawGizmos()
{
for (var x = -circleRadius; x <= circleRadius; x++)
{
for (var y = -circleRadius; y <= circleRadius; y++)
{
var pos = new Vector3(x, 0f, y);
if (pos.magnitude >= circleRadius) continue;
Gizmos.DrawSphere(pos * (objectSize * 2f), objectSize);
}
}
}

How can I fix this imperfect circle I made using LineRenderer?

So I made this shape which I applied to a sprite via this script:
using UnityEngine;
using System.Collections;
public class CircleShapeGenerator : MonoBehaviour
{
public int segments = 100;
public float radius = 1;
public Color c1 = new Color( 1, 1, 1, 0.1f );
public Color c2 = new Color( 1, 1, 1, 0.1f );
LineRenderer line;
void Start ()
{
line = gameObject.AddComponent<LineRenderer>();
line.material = new Material(Shader.Find("Particles/Additive"));
line.SetWidth(0.05F, 0.05F);
line.SetVertexCount (segments + 1);
line.useWorldSpace = false;
}
void Update()
{
line.SetColors(c1, c2);
float angle = 20f;
for (int i = 0; i < (segments + 1); i++)
{
float x = Mathf.Sin (Mathf.Deg2Rad * angle) * radius;
float y = Mathf.Cos (Mathf.Deg2Rad * angle) * radius;
line.SetPosition( i, new Vector3( x,y,0) );
angle += (360f / segments);
}
}
}
As you can see in the screenshot, the start and end do not connect as they should. How can I fix this? I found this snippet of code on the entire internet but all give this result. Can somebody fix this or provide, perhaps, a spline solution? I think its overkill to go to a Shader solution (0 experience with shaders).
This solution could be a little bit complicated. But it'll works.
The idea is
1) Draw first segment as small segmented area.
2) Draw from seconds to last -1 segments as big segment.
3) Draw last segment as small segmented area too.
It makes seamless edge between the start segment and the end segment.
And total segment's count is not too many.
total segment = segment + 2 * subsegment
This is sample code.
using UnityEngine;
using System.Collections;
public class CircleShapeGenerator : MonoBehaviour {
public int segments = 100;
public int edgeSegments = 10;
public float radius = 1f;
int vertCount;
float increAngle, increAngleEdge;
public Color c1 = new Color( 1, 1, 1, 1f );
public Color c2 = new Color( 1, 1, 1, 1f );
LineRenderer line;
void Start ()
{
vertCount = segments + 2*edgeSegments - 2 + 1;
increAngle = 360f / segments;
increAngleEdge = increAngle/edgeSegments;
line = gameObject.AddComponent<LineRenderer>();
line.material = new Material(Shader.Find("Particles/Additive"));
line.SetWidth(0.05F, 0.05F);
line.SetVertexCount (vertCount);
line.useWorldSpace = false;
}
void Update()
{
line.SetColors(c1, c2);
//draw first segment
float angle = 0;
for (int i = 0; i < edgeSegments; i++)
{
float x = Mathf.Sin (Mathf.Deg2Rad * angle) * radius;
float y = Mathf.Cos (Mathf.Deg2Rad * angle) * radius;
line.SetPosition( i, new Vector3(x, y, 0) );
angle += increAngleEdge;
}
//draw from seconds to last-1 segment
angle -= increAngleEdge;
for (int i = 0; i < segments-2; i++)
{
angle += increAngle;
float x = Mathf.Sin (Mathf.Deg2Rad * angle) * radius;
float y = Mathf.Cos (Mathf.Deg2Rad * angle) * radius;
line.SetPosition( edgeSegments + i, new Vector3(x, y, 0) );
}
//draw last segment
for (int i = 0; i < edgeSegments+1; i++)
{
angle += increAngleEdge;
float x = Mathf.Sin (Mathf.Deg2Rad * angle) * radius;
float y = Mathf.Cos (Mathf.Deg2Rad * angle) * radius;
line.SetPosition( edgeSegments + segments - 2 + i, new Vector3(x, y, 0) );
}
}
}

Categories