How to make a spiral rotate? - rotation

I have successfully coded a static spiral using lines, and now I'm supposed to make the spiral rotate from frame to frame. I tried incrementing the angle used for the x and y positions of the end of the lines with each frame, but the spiral doesn't move at all.
void draw() {
for (int i = 0; i < 15 * NUM_LINES; i++) {
float lineEndX = width / 2 + radius * cos(angle + startAngle);
float lineEndY = height / 2 + radius * sin(angle + startAngle);
line (lineStartX, lineStartY, lineEndX, lineEndY);
lineStartX = lineEndX;
lineStartY = lineEndY;
radius = radius + 0.047;
angle += 0.01 % (TWO_PI * NUM_TURNS);
}
startAngle += START_ANGLE_CHANGE;
angle = 0;
}

Add background(255); to your draw function. Also define lineStartX, lineStartY and radius there so their values are reset every time the function is called.
void draw() {
background(255);
float lineEndX = width / 2;
float lineEndY = height / 2;
float radius = 5;
for (int i = 0; i < 15 * NUM_LINES; i++) {
float lineEndX = width / 2 + radius * cos(angle + startAngle);
float lineEndY = height / 2 + radius * sin(angle + startAngle);
line (lineStartX, lineStartY, lineEndX, lineEndY);
lineStartX = lineEndX;
lineStartY = lineEndY;
radius = radius + 0.047;
angle += 0.01 % (TWO_PI * NUM_TURNS);
}
startAngle += START_ANGLE_CHANGE;
angle = 0;
}
Working example here.

Related

Unity - Improve Mesh generation and rendering performance

since I just recently started looking into meshes, how they work, what they do and so on, I decided to use my own calculations to create a mesh of a circle. Unfortunately though, this is really, really slow!
So I am looking for tips on improvements, to make it slow only (because that's probably the best it will get...)
Here is the code I use to generate a circle:
public static void createCircle(MeshFilter meshFilter, float innerRadius, float outerRadius, Color color, float xPosition = 0, float yPosition = 0, float startDegree = 0, float endDegree = 360, int points = 100)
{
Mesh mesh = meshFilter.mesh;
mesh.Clear();
//These values will result in no (or very ugly in the case of points < 10) circle, so let's safe calculation and just return an empty mesh!
if (startDegree == endDegree || points < 10 || innerRadius >= outerRadius || innerRadius < 0 || outerRadius <= 0)
{
return;
}
//The points for the full circle shall be whatever is given but if its not the full circle we dont need all the points!
points = (int)(Mathf.Abs(endDegree - startDegree) / 360f * points);
//We always need an uneven number of points!
if (points % 2 != 0) { points++; }
Vector3[] vertices = new Vector3[points];
float degreeStepSize = (endDegree - startDegree) * 2 / (points - 3);
float halfRadStepSize = (degreeStepSize) * Mathf.Deg2Rad / 2f;
float startRad = Mathf.Deg2Rad * startDegree;
float endRad = Mathf.Deg2Rad * endDegree;
//Let's save the vector at the beginning and the one on the end to make a perfectly straight line
vertices[0] = new Vector3(Mathf.Sin(startRad) * outerRadius + xPosition, Mathf.Cos(startRad) * outerRadius + yPosition, 0);
vertices[vertices.Length - 1] = new Vector3(Mathf.Sin(endRad) * innerRadius + xPosition, Mathf.Cos(endRad) * innerRadius + yPosition, 0);
for (int i = 1; i < vertices.Length - 1; i++)
{
//Pure coinsidence that saved some calculatons. Half Step Size is the same as what would needed to be calculated here!
float rad = (i - 1) * halfRadStepSize + startRad;
if (i % 2 == 0)
{
vertices[i] = new Vector3(Mathf.Sin(rad) * outerRadius + xPosition, Mathf.Cos(rad) * outerRadius + yPosition, 0);
}
else
{
vertices[i] = new Vector3(Mathf.Sin(rad) * innerRadius + xPosition, Mathf.Cos(rad) * innerRadius + yPosition, 0);
}
}
mesh.vertices = vertices;
int[] tri = new int[(vertices.Length - 2) * 3];
for (int i = 0; i < (vertices.Length - 2); i++)
{
int index = i * 3;
if (i % 2 == 0)
{
tri[index + 0] = i + 0;
tri[index + 1] = i + 2;
tri[index + 2] = i + 1;
}
else
{
tri[index + 0] = i + 0;
tri[index + 1] = i + 1;
tri[index + 2] = i + 2;
}
}
mesh.triangles = tri;
Vector3[] normals = new Vector3[vertices.Length];
Color[] colors = new Color[vertices.Length];
for (int i = 0; i < vertices.Length; i++)
{
normals[i] = Vector3.forward;
colors[i] = color;
}
mesh.normals = normals;
mesh.colors = colors;
meshFilter.mesh = mesh;
}
I know I "could just use the LineRenderer shipped with Unity, it is faster then anything you'll ever write", but that's not the point here.
I am trying to understand meshes and see where I can tweak my code to improve it's performance.
Thanks for your help in advance!
You can almost double the speed by removing extra memory allocation. Since Vector3 is a value type, they are already allocated when you allocate the array. Vector3.forward also allocates a new Vector3 each time, and we can re-use it.
public static void createCircle(MeshFilter meshFilter, float innerRadius, float outerRadius, Color color, float xPosition = 0, float yPosition = 0, float startDegree = 0, float endDegree = 360, int points = 100)
{
Mesh mesh = meshFilter.mesh;
mesh.Clear();
//These values will result in no (or very ugly in the case of points < 10) circle, so let's safe calculation and just return an empty mesh!
if (startDegree == endDegree || points < 10 || innerRadius >= outerRadius || innerRadius < 0 || outerRadius <= 0)
{
return;
}
//The points for the full circle shall be whatever is given but if its not the full circle we dont need all the points!
points = (int)(Mathf.Abs(endDegree - startDegree) / 360f * points);
//We always need an uneven number of points!
if (points % 2 != 0) { points++; }
Vector3[] vertices = new Vector3[points];
float degreeStepSize = (endDegree - startDegree) * 2 / (points - 3);
float halfRadStepSize = (degreeStepSize) * Mathf.Deg2Rad / 2f;
float startRad = Mathf.Deg2Rad * startDegree;
float endRad = Mathf.Deg2Rad * endDegree;
//Let's save the vector at the beginning and the one on the end to make a perfectly straight line
vertices[0] = new Vector3(Mathf.Sin(startRad) * outerRadius + xPosition, Mathf.Cos(startRad) * outerRadius + yPosition, 0);
vertices[vertices.Length - 1] = new Vector3(Mathf.Sin(endRad) * innerRadius + xPosition, Mathf.Cos(endRad) * innerRadius + yPosition, 0);
for (int i = 1; i < vertices.Length - 1; i++)
{
//Pure coinsidence that saved some calculatons. Half Step Size is the same as what would needed to be calculated here!
float rad = (i - 1) * halfRadStepSize + startRad;
if (i % 2 == 0)
{
vertices[i].x = Mathf.Sin(rad) * outerRadius + xPosition;
vertices[i].y = Mathf.Cos(rad) * outerRadius + yPosition;
vertices[i].z = 0;
}
else
{
vertices[i].x = Mathf.Sin(rad) * innerRadius + xPosition;
vertices[i].y = Mathf.Cos(rad) * innerRadius + yPosition;
vertices[i].z = 0;;
}
}
mesh.vertices = vertices;
int[] tri = new int[(vertices.Length - 2) * 3];
for (int i = 0; i < (vertices.Length - 2); i++)
{
int index = i * 3;
if (i % 2 == 0)
{
tri[index + 0] = i + 0;
tri[index + 1] = i + 2;
tri[index + 2] = i + 1;
}
else
{
tri[index + 0] = i + 0;
tri[index + 1] = i + 1;
tri[index + 2] = i + 2;
}
}
mesh.triangles = tri;
Vector3[] normals = new Vector3[vertices.Length];
Color[] colors = new Color[vertices.Length];
var f = Vector3.forward;
for (int i = 0; i < vertices.Length; i++)
{
normals[i].x= f.x;
normals[i].y= f.y;
normals[i].z= f.z;
colors[i] = color;
}
mesh.normals = normals;
mesh.colors = colors;
meshFilter.mesh = mesh;
}

Calculating points around circle

I have a Big Circle and several small circles around it as seen in picture
First I'm drawing middle small circle like this:
cxSmallMiddle = cxBig + radiusBig + hDist + radiusSmall;
sySmallMiddle = radiusBig;
cxBig is center of Big circle. hDist is the distance I want every small circle to be from big circle.
So this way now middle small circle's middle point is parallel to big circle's.
Now I want to draw next small circle with hDist from big circle and vDist (vertical distance) from middle small circle.
So this way hDist and vDist will control the distance small circles are separated from big circle and gap between small circles accordingly.
how can I find cx and cy for other buttons?
This is a hand drawn finished version
Edit: added a code suggested by #Gene
#Override
public void onDraw(Canvas canvas) {
float radiusBig = 110f * singleDp;
float cxBig = screenWidth / 2f;
//float cyBig = screenHeight / 2f;
float cyBig = radiusBig + strokeWidth + (20*singleDp);
canvas.drawCircle(cxBig, cyBig, radiusBig, paint);
float radiusSmall = 20 * singleDp;
float vDist = 0 * singleDp;
float hDist = 0 * singleDp;
float acPoint = radiusBig;
float bcPoint = radiusSmall + vDist;
float theta = (float) Math.acos(bcPoint / acPoint);
int i = 0;
double x_i = acPoint * Math.cos(i * theta) + cxBig;
double y_i = acPoint * Math.sin(i * theta) + cyBig;
canvas.drawCircle((float) x_i, (float) y_i, radiusSmall, paint);
i = 1;
x_i = acPoint * Math.cos(i * theta) + cxBig;
y_i = acPoint * Math.sin(i * theta) + cyBig;
canvas.drawCircle((float) x_i, (float) y_i, radiusSmall, paint);
}
I experimented a lot with this code and this is what I got. When I draw i=0 is almost 45 degree distance from i=0. While experimenting, I discovered if I specify vDist = 80; then it looks okay. The bigger the vDist the closer it gets to i=0.
This is high school trigonometry. There's a right triangle formed by the big circle center (A), the small circle center (C), and the point (B) on the horizontal radius directly below the small circle center.
The length of edge BC is vDist + 2 * radiusSmall. The length of AC is radiusBig
Let \theta be the angle BAC. Then
sin(\theta) = BC / AC = (vDist + 2 * radiusSmall) / radiusBig.
So you can determine \theta:
\theta = arcsin((vDist + radiusSmall) / radiusBig)
Once you have \theta, the locations of the circles wrt the origin are
x_i = radiusBig * cos(i * \theta)
y_i = radiusBig * sin(i * \theta)
For i = 0, +1, -1, +2, -2, ...
Edit
Okay here is a quick hack in Java Swing. Sorry in the original post I said arccos when I meant arcsin.
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Circles extends JPanel {
public static void main(String[] a) {
JFrame f = new JFrame();
f.setSize(800, 800);
f.add(new Circles());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
#Override
public void paint(Graphics g) {
int cx = 400, cy = 400, rBig = 200, rSmall = 40, hDist = 20, vDist = 10;
drawCircle(g, cx, cy, rBig); // Big circle.
int rSmallCircleCenters = rBig + hDist + rSmall;
double theta = Math.asin(((double) vDist + 2 * rSmall) / rSmallCircleCenters);
int nPairs = 3;
for (int i = 1 - nPairs; i < nPairs; ++i) {
int dx = (int) (rSmallCircleCenters * Math.cos(i * theta));
int dy = (int) (rSmallCircleCenters * Math.sin(i * theta));
drawCircle(g, cx + dx, cy + dy, rSmall);
drawCircle(g, cx - dx, cy - dy, rSmall);
}
}
private void drawCircle(Graphics g, int cx, int cy, int r) {
g.drawOval(cx - r, cy - r, 2 * r, 2 * r);
}
}
Here's what it draws:

Processing PVector rotations

The issue is i got an array of PVectors placed around my main PVector which is in the middle. I want my array of PVectors to rotate around my main PVector based on a rotation variable. Is there any way to do this?
Right now I have this code but it does not rotate the PVectors, just places them farther away based on the rotation var.
class Box {
PVector location;
PVector[] points;
float rotation = random(360);
Box() {
location = new PVector(random(width), random(height));
points = new PVector[4];
for(a = 0; a < points.length; a ++) {
points[a] = new PVector(0,0);
}
}
void update() {
points[0].x = location.x + 10 * sin(rotation);
points[0].y = location.y + 10 * sin(rotation);
points[1].x = location.x + 10 * sin(rotation);
points[1].y = location.y - 10 * sin(rotation);
points[2].x = location.x - 10 * sin(rotation);
points[2].y = location.y + 10 * sin(rotation);
points[3].x = location.x - 10 * sin(rotation);
points[3].y = location.y - 10 * sin(rotation);
}
To rotate the vectors, you do need to use trig functions like sin and cos like you have in your code. However, your approach isn't really the best. Adding onto the existing (x,y) coordinates on each update isn't really feasible, since the number you have to add on is changing every time. It's easier just to overwrite and calculate new values for each update. The x and y coordinates for a given angle are given by the unit circle:
So, the x of a given PVector varies with cos(theta) and the y varies with sin(theta). Check the following code:
Box b;
void setup(){
size(300,300);
b = new Box();
}
void draw(){
background(255);
b.update(mouseX, mouseY);
b.display();
}
class Box {
PVector location;
PVector[] points;
float rotation;
float radius;
Box() {
location = new PVector(width/2,height/2);
points = new PVector[7];
rotation = 0;
radius = 50;
for(int i = 0; i < points.length; i ++) {
//this centers the points around (0,0), so you need to add in
//the box coordinates later on.
points[i] = new PVector(radius*cos(rotation + i*TWO_PI/points.length),
radius*sin(rotation + i*TWO_PI/points.length));
}
}
void update(int x, int y) {
location.set(x,y);
rotation += 0.08; // change for different rotation speeds.
for(int i = 0; i < points.length; i++){
points[i].set(radius*cos(rotation + i*TWO_PI/points.length),
radius*sin(rotation + i*TWO_PI/points.length));
}
}
void display(){
stroke(0);
for(int i = 0; i < points.length; i++){
//points are treated as offsets from the center point:
line(location.x,location.y,location.x+points[i].x,location.y+points[i].y);
ellipse(location.x+points[i].x,location.y+points[i].y,10,10);
}
}
}
For every update() call, it increments the rotation variable and calculates the new x and y values for each point in the array. You can change the speed and direction of rotation by changing 0.08 to bigger/smaller/positive/negative numbers.
To rotate a point around location:
double x = cos(rotation) * (point.x-location.x) - sin(rotation) * (point.y-location.y) + location.x;
double y = sin(rotation) * (point.x-location.x) + cos(rotation) * (point.y-location.y) + location.y;
point.x = x;
point.y = y;
See Rotate a point by an angle

Tinting a terrain model in a radius around a given point in XNA 4.0

I'm writing a game in Visual Studio 2010, using the XNA 4.0 framework. I have a 3D terrain model generated from a height map. What I'm trying to accomplish is to tint this model in a given radius around a certain point, the end goal being to display to the player the radius in which a unit can move in a given turn. The method I'm using to draw the model at the moment is this:
void DrawModel(Model model, Matrix worldMatrix)
{
Matrix[] boneTransforms = new Matrix[model.Bones.Count];
model.CopyAbsoluteBoneTransformsTo(boneTransforms);
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = boneTransforms[mesh.ParentBone.Index] * worldMatrix;
effect.View = camera.viewMatrix;
effect.Projection = camera.projectionMatrix;
effect.EnableDefaultLighting();
effect.EmissiveColor = Color.Green.ToVector3();
effect.PreferPerPixelLighting = true;
// Set the fog to match the black background color
effect.FogEnabled = true;
effect.FogColor = Color.CornflowerBlue.ToVector3();
effect.FogStart = 1000;
effect.FogEnd = 3200;
}
mesh.Draw();
}
}
Also, in case it's relevant, I followed this tutorial http://create.msdn.com/en-US/education/catalog/sample/collision_3d_heightmap to create my heightmap and terrain.
Thanks in advance for any help!
You can use a shader to achieve that...
you only would need to pass as argument the world position of the center and the radius,
and let the pixel shader receive the pixel world position interpolated from the vertex shader as a texture coord...
then only have to check the distance of the pixel position to the center and tint it with a color if the pixel position is in range...
The technique you are looking for is called decaling.
You have to extract the part of the terrain, where the circle will be drawn, apply an appropriate texture to that part and draw it blending it with the terrain.
For the case of a terrain based on a uniform grid, this will look like the following:
You have the center position of the decal and its radius. Then you can determine min and max row/col in the grid, so that the cells include every drawn region. Create a new vertex buffer from these vertices. Positions can be read from the heightmap. You have to alter the texture coordinates, so the texture will be placed at the right position. Assume, the center position has coordinate (0.5, 0.5), center position + (radius, radius) has coordinate (1, 1) and so on. With that you should be able to find an equation for the texture coordinates for each vertex.
In the above example, the top left red vertex has texture coordinates of about (-0.12, -0.05)
Then you have the subgrid of the terrain. Apply the decal texture to it. Set an appropriate depth bias (you have to try out some values). In most cases, a negative SlopeScaleDepthBias will work. Turn off texture coordinate wrapping in the sampler. Draw the subgrid.
Here's some VB SlimDX Code I wrote for that purpose:
Public Sub Init()
Verts = (Math.Ceiling(2 * Radius / TriAngleWidth) + 2) ^ 2
Tris = (Math.Ceiling(2 * Radius / TriAngleWidth) + 1) ^ 2 * 2
Dim Indices(Tris * 3 - 1) As Integer
Dim curN As Integer
Dim w As Integer
w = (Math.Ceiling(2 * Radius / TriAngleWidth) + 2)
For y As Integer = 0 To w - 2
For x As Integer = 0 To w - 2
Indices(curN) = x + y * w : curN += 1
Indices(curN) = x + (y + 1) * w : curN += 1
Indices(curN) = (x + 1) + (y) * w : curN += 1
Indices(curN) = x + (y + 1) * w : curN += 1
Indices(curN) = (x + 1) + (y + 1) * w : curN += 1
Indices(curN) = (x + 1) + y * w : curN += 1
Next
Next
VB = New Buffer(D3DDevice, New BufferDescription(Verts * VertexPosTexColor.Struct.SizeOfBytes, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, VertexPosTexColor.Struct.SizeOfBytes))
IB = New Buffer(D3DDevice, New DataStream(Indices, False, False), New BufferDescription(4 * Tris * 3, ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 4))
End Sub
Public Sub Update()
Dim Vertex(Verts - 1) As VertexPosTexColor.Struct
Dim curN As Integer
Dim rad As Single 'The decal radius
Dim height As Single
Dim p As Vector2
Dim yx, yz As Integer
Dim t As Vector2 'texture coordinates
Dim center As Vector2 'decal center
For y As Integer = Math.Floor((center.Y - rad) / TriAngleWidth) To Math.Floor((center.Y - rad) / TriAngleWidth) + Math.Ceiling(2 * rad / TriAngleWidth) + 1
For x As Integer = Math.Floor((center.X - rad) / TriAngleWidth) To Math.Floor((center.X - rad) / TriAngleWidth) + Math.Ceiling(2 * rad / TriAngleWidth) + 1
p.X = x * TriAngleWidth
p.Y = y * TriAngleWidth
yx = x : yz = y
If yx < 0 Then yx = 0
If yx > HeightMap.GetUpperBound(0) Then yx = HeightMap.GetUpperBound(0)
If yz < 0 Then yz = 0
If yz > HeightMap.GetUpperBound(1) Then yz = HeightMap.GetUpperBound(1)
height = HeightMap(yx, yz)
t.X = (p.X - center.X) / (2 * rad) + 0.5
t.Y = (p.Y - center.Y) / (2 * rad) + 0.5
Vertex(curN) = New VertexPosTexColor.Struct With {.Position = New Vector3(p.X, hoehe, p.Y), .TexCoord = t, .Color = New Color4(1, 1, 1, 1)} : curN += 1
Next
Next
Dim data = D3DContext.MapSubresource(VB, MapMode.WriteDiscard, MapFlags.None)
data.Data.WriteRange(Vertex)
D3DContext.UnmapSubresource(VB, 0)
End Sub
And here's the according C# code.
public void Init()
{
Verts = Math.Pow(Math.Ceiling(2 * Radius / TriAngleWidth) + 2, 2);
Tris = Math.Pow(Math.Ceiling(2 * Radius / TriAngleWidth) + 1, 2) * 2;
int[] Indices = new int[Tris * 3];
int curN;
int w;
w = (Math.Ceiling(2 * Radius / TriAngleWidth) + 2);
for(int y = 0; y <= w - 2; ++y)
{
for(int x = 0; x <= w - 2; ++x)
{
Indices[curN] = x + y * w ; curN += 1;
Indices[curN] = x + (y + 1) * w ; curN += 1;
Indices[curN] = (x + 1) + (y) * w ; curN += 1;
Indices[curN] = x + (y + 1) * w ; curN += 1;
Indices[curN] = (x + 1) + (y + 1) * w ; curN += 1;
Indices[curN] = (x + 1) + y * w ; curN += 1;
}
}
VB = new Buffer(D3DDevice, new BufferDescription(Verts * VertexPosTexColor.Struct.SizeOfBytes, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, VertexPosTexColor.Struct.SizeOfBytes));
IB = new Buffer(D3DDevice, new DataStream(Indices, False, False), new BufferDescription(4 * Tris * 3, ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 4));
}
public void Update()
{
VertexPosTexColor.Struct[] Vertex = new VertexPosTexColor.Struct[Verts] ;
int curN;
float rad; //The decal radius
float height;
Vector2 p;
int yx, yz;
Vector2 t; //texture coordinates
Vector2 center; //decal center
for(int y = Math.Floor((center.Y - rad) / TriAngleWidth); y <= Math.Floor((center.Y - rad) / TriAngleWidth) + Math.Ceiling(2 * rad / TriAngleWidth) + 1; ++y)
for(int x = Math.Floor((center.X - rad) / TriAngleWidth); x <= Math.Floor((center.X - rad) / TriAngleWidth) + Math.Ceiling(2 * rad / TriAngleWidth) + 1; ++x)
{
p.X = x * TriAngleWidth;
p.Y = y * TriAngleWidth;
yx = x ; yz = y;
if( yx < 0)
yx = 0;
if (yx > HeightMap.GetUpperBound(0))
yx = HeightMap.GetUpperBound(0);
if (yz < 0)
yz = 0;
if (yz > HeightMap.GetUpperBound(1))
yz = HeightMap.GetUpperBound(1);
height = HeightMap[yx, yz];
t.X = (p.X - center.X) / (2 * rad) + 0.5;
t.Y = (p.Y - center.Y) / (2 * rad) + 0.5;
Vertex[curN] = new VertexPosTexColor.Struct() {Position = new Vector3(p.X, hoehe, p.Y), TexCoord = t, Color = New Color4(1, 1, 1, 1)}; curN += 1;
}
}
var data = D3DContext.MapSubresource(VB, MapMode.WriteDiscard, MapFlags.None);
data.Data.WriteRange(Vertex);
D3DContext.UnmapSubresource(VB, 0);
}

Calculating the position of points in a circle

I'm having a bit of a mind blank on this at the moment.
I've got a problem where I need to calculate the position of points around a central point, assuming they're all equidistant from the center and from each other.
The number of points is variable so it's DrawCirclePoints(int x)
I'm sure there's a simple solution, but for the life of me, I just can't see it :)
Given a radius length r and an angle t in radians and a circle's center (h,k), you can calculate the coordinates of a point on the circumference as follows (this is pseudo-code, you'll have to adapt it to your language):
float x = r*cos(t) + h;
float y = r*sin(t) + k;
A point at angle theta on the circle whose centre is (x0,y0) and whose radius is r is (x0 + r cos theta, y0 + r sin theta). Now choose theta values evenly spaced between 0 and 2pi.
Here's a solution using C#:
void DrawCirclePoints(int points, double radius, Point center)
{
double slice = 2 * Math.PI / points;
for (int i = 0; i < points; i++)
{
double angle = slice * i;
int newX = (int)(center.X + radius * Math.Cos(angle));
int newY = (int)(center.Y + radius * Math.Sin(angle));
Point p = new Point(newX, newY);
Console.WriteLine(p);
}
}
Sample output from DrawCirclePoints(8, 10, new Point(0,0));:
{X=10,Y=0}
{X=7,Y=7}
{X=0,Y=10}
{X=-7,Y=7}
{X=-10,Y=0}
{X=-7,Y=-7}
{X=0,Y=-10}
{X=7,Y=-7}
Good luck!
Placing a number in a circular path
// variable
let number = 12; // how many number to be placed
let size = 260; // size of circle i.e. w = h = 260
let cx= size/2; // center of x(in a circle)
let cy = size/2; // center of y(in a circle)
let r = size/2; // radius of a circle
for(let i=1; i<=number; i++) {
let ang = i*(Math.PI/(number/2));
let left = cx + (r*Math.cos(ang));
let top = cy + (r*Math.sin(ang));
console.log("top: ", top, ", left: ", left);
}
Using one of the above answers as a base, here's the Java/Android example:
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
RectF bounds = new RectF(canvas.getClipBounds());
float centerX = bounds.centerX();
float centerY = bounds.centerY();
float angleDeg = 90f;
float radius = 20f
float xPos = radius * (float)Math.cos(Math.toRadians(angleDeg)) + centerX;
float yPos = radius * (float)Math.sin(Math.toRadians(angleDeg)) + centerY;
//draw my point at xPos/yPos
}
For the sake of completion, what you describe as "position of points around a central point(assuming they're all equidistant from the center)" is nothing but "Polar Coordinates". And you are asking for way to Convert between polar and Cartesian coordinates which is given as x = r*cos(t), y = r*sin(t).
PHP Solution:
class point{
private $x = 0;
private $y = 0;
public function setX($xpos){
$this->x = $xpos;
}
public function setY($ypos){
$this->y = $ypos;
}
public function getX(){
return $this->x;
}
public function getY(){
return $this->y;
}
public function printX(){
echo $this->x;
}
public function printY(){
echo $this->y;
}
}
function drawCirclePoints($points, $radius, &$center){
$pointarray = array();
$slice = (2*pi())/$points;
for($i=0;$i<$points;$i++){
$angle = $slice*$i;
$newx = (int)($center->getX() + ($radius * cos($angle)));
$newy = (int)($center->getY() + ($radius * sin($angle)));
$point = new point();
$point->setX($newx);
$point->setY($newy);
array_push($pointarray,$point);
}
return $pointarray;
}
Here is how I found out a point on a circle with javascript, calculating the angle (degree) from the top of the circle.
const centreX = 50; // centre x of circle
const centreY = 50; // centre y of circle
const r = 20; // radius
const angleDeg = 45; // degree in angle from top
const radians = angleDeg * (Math.PI/180);
const pointY = centreY - (Math.cos(radians) * r); // specific point y on the circle for the angle
const pointX = centreX + (Math.sin(radians) * r); // specific point x on the circle for the angle
I had to do this on the web, so here's a coffeescript version of #scottyab's answer above:
points = 8
radius = 10
center = {x: 0, y: 0}
drawCirclePoints = (points, radius, center) ->
slice = 2 * Math.PI / points
for i in [0...points]
angle = slice * i
newX = center.x + radius * Math.cos(angle)
newY = center.y + radius * Math.sin(angle)
point = {x: newX, y: newY}
console.log point
drawCirclePoints(points, radius, center)
Here is an R version based on the #Pirijan answer above.
points <- 8
radius <- 10
center_x <- 5
center_y <- 5
drawCirclePoints <- function(points, radius, center_x, center_y) {
slice <- 2 * pi / points
angle <- slice * seq(0, points, by = 1)
newX <- center_x + radius * cos(angle)
newY <- center_y + radius * sin(angle)
plot(newX, newY)
}
drawCirclePoints(points, radius, center_x, center_y)
The angle between each of your points is going to be 2Pi/x so you can say that for points n= 0 to x-1 the angle from a defined 0 point is 2nPi/x.
Assuming your first point is at (r,0) (where r is the distance from the centre point) then the positions relative to the central point will be:
rCos(2nPi/x),rSin(2nPi/x)
Working Solution in Java:
import java.awt.event.*;
import java.awt.Robot;
public class CircleMouse {
/* circle stuff */
final static int RADIUS = 100;
final static int XSTART = 500;
final static int YSTART = 500;
final static int DELAYMS = 1;
final static int ROUNDS = 5;
public static void main(String args[]) {
long startT = System.currentTimeMillis();
Robot bot = null;
try {
bot = new Robot();
} catch (Exception failed) {
System.err.println("Failed instantiating Robot: " + failed);
}
int mask = InputEvent.BUTTON1_DOWN_MASK;
int howMany = 360 * ROUNDS;
while (howMany > 0) {
int x = getX(howMany);
int y = getY(howMany);
bot.mouseMove(x, y);
bot.delay(DELAYMS);
System.out.println("x:" + x + " y:" + y);
howMany--;
}
long endT = System.currentTimeMillis();
System.out.println("Duration: " + (endT - startT));
}
/**
*
* #param angle
* in degree
* #return
*/
private static int getX(int angle) {
double radians = Math.toRadians(angle);
Double x = RADIUS * Math.cos(radians) + XSTART;
int result = x.intValue();
return result;
}
/**
*
* #param angle
* in degree
* #return
*/
private static int getY(int angle) {
double radians = Math.toRadians(angle);
Double y = RADIUS * Math.sin(radians) + YSTART;
int result = y.intValue();
return result;
}
}
Based on the answer above from Daniel, here's my take using Python3.
import numpy
def circlepoints(points,radius,center):
shape = []
slice = 2 * 3.14 / points
for i in range(points):
angle = slice * i
new_x = center[0] + radius*numpy.cos(angle)
new_y = center[1] + radius*numpy.sin(angle)
p = (new_x,new_y)
shape.append(p)
return shape
print(circlepoints(100,20,[0,0]))

Resources