- Home /
Spawning a BoxCollider2D between 2 vector3 (JS)
So I am working on a game where a user will draw a line (got that part working) by using input.touch. What I want to have happen is have a BoxColider2D to spawn in the center of the line segment at the correct rotation to match up with the line. I think I can figure out how to spawn it in the center of the line segment but what I don't understand is spawning it at the correct rotation.
Here is the test script I am using to work out core functionality (JavaScript):
#pragma strict
var lastDotPosition : Vector3;
var lastPointExists : boolean = false;
var c1 : Color = Color.yellow;
var c2 : Color = Color.red;
var lengthOfLineRenderer : int = 2;
function Start() {
var lineRenderer : LineRenderer = gameObject.AddComponent.<LineRenderer>();
lineRenderer.material = new Material (Shader.Find("Particles/Additive"));
lineRenderer.SetColors(c1, c2);
lineRenderer.SetWidth(0.01,0.01);
lineRenderer.SetVertexCount(lengthOfLineRenderer);
}
function Update()
{
if (Input.GetMouseButton(0))
{
var lineRenderer : GameObject = new GameObject("Line");
lineRenderer.AddComponent.<LineRenderer>();
var newLine : LineRenderer = lineRenderer.GetComponent.<LineRenderer>();
newLine.SetColors(c1, c2);
newLine.SetWidth(0.1,0.1);
newLine.SetVertexCount(lengthOfLineRenderer);
var mouse : Vector2 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var mouseRay : Ray2D = new Ray2D(mouse, Vector2.zero);
var newDotPosition : Vector2 = mouseRay.origin;
lineRenderer.AddComponent.<BoxCollider2D>();
var newCol : BoxCollider2D = lineRenderer.GetComponent.<BoxCollider2D>();
if (newDotPosition != lastDotPosition)
{
var pos : Vector3 = Vector3(lastDotPosition.x,lastDotPosition.y, 0);
newLine.SetPosition(0, pos);
var pos2 : Vector3 = Vector3(newDotPosition.x, newDotPosition.y, 0);
newLine.SetPosition(1, pos2);
newCol.size = Vector2(1, .1);
var colAngle : float = Vector3.Dot(pos,pos2);
colAngle = colAngle/(pos.magnitude*pos2.magnitude);
colAngle = Mathf.Acos(colAngle);
colAngle = colAngle*180/Mathf.PI;
Debug.Log("Col angle: " + colAngle);
lineRenderer.transform.Rotate(Vector3(0, 0, colAngle+17.28));
Debug.Log("Rotation: " + lineRenderer.transform.rotation.z);
lastDotPosition = newDotPosition;
}
}
}
I figured out how to calculate the angle between the two vectors that represent the endpoints of the line segment; pos (point start) and pos2 (point end). What I don't get is getting the gameobject/collider to rotate to that degree. The angle between the two vectors is the var colAngle. Please tell me if I am calculating the angle correctly. If yes then how am I supposed to make the BoxCollider2D rotate to the correct rotation.
To test it just attach this script to an new empty gameobject and run it.
Thanks for your time and ALL answers are appreciated!