clamp position 1/4 of a circle 2D
I want to Make script where 2D object moves in 1/4th of a circle, Quarter 1 of a circle. with maximum distance is 4.0f for example.
what I could do 2D java script not much.
private var pos : Vector2;
var cannons : Transform;
var maxDistance : float = 4.0f;
function Start () {
}
function Update () {
var dist = Vector2.Distance(cannons.position, transform.position);
if(maxDistance < dist){
dist = maxDistance;
}
print ("Distance to other: " + dist);
if (Input.touchCount > 0){
pos = Camera.main.ScreenToWorldPoint (Vector2 (Input.GetTouch(0).position.x, Input.GetTouch(0).position.y));
pos.x = Mathf.Clamp(pos.x,-8.5,-4.5);
pos.y = Mathf.Clamp(pos.y,-2.25,1.75);
transform.position = new Vector2(pos.x, pos.y);
}
}
-heart must move inside the 1/4 of the circle freely
-if touch position is outside the circle zone it must move to closest position to that touch position (star)
- the center of the movement must be smiley face clearly.
i tried many solutions but all had errors probably it was my mistake as I am new to the awesome Unity3d scripting.
Answer by MuradD · Mar 14, 2016 at 09:37 AM
I solved this issue and here is my code;
using UnityEngine;
using System.Collections;
public class CorsairMover : MonoBehaviour {
RaycastHit hit;
public Transform Tank;
public Transform corsair;
//private Transform temp;
float TankX;
float TankY;
float TankX2;
float TankY2;
void Start () {
TankX = Tank.position.x;
TankY = Tank.position.y;
TankX2 = TankX + 4;
TankY2 = TankY + 4;
}
void Update () {
Ray2D x = new Ray2D(Tank.position, Input.mousePosition - Camera.main.WorldToScreenPoint(Tank.position));
Debug.Log("Ray Origin : " + x.origin + " direction : " + x.direction);
float distanceFromCanon = Vector2.Distance(Input.mousePosition, Camera.main.WorldToScreenPoint(Tank.position)) * 0.03f;
Debug.Log(distanceFromCanon.ToString());
distanceFromCanon = Mathf.Clamp(distanceFromCanon, 0f, 4f);
//corsair.position = x.GetPoint(distanceFromCanon);
Vector2 temp = x.GetPoint(distanceFromCanon);
temp.x = Mathf.Clamp(temp.x, TankX, TankX2);
temp.y = Mathf.Clamp(temp.y, TankY, TankY2);
corsair.position = temp;
}
}
and I am using static position for my tank thats why if it moves it will only take initial position as clamping reference; // not tested but you can move start() function contents to update to make it follow tank.position
Your answer
Follow this Question
Related Questions
Factorio-like sprite directions 0 Answers
"Invalid argument"? 0 Answers
Player Not Moving With Platform 2D 1 Answer
How can i do an action after i detect a collision2D && and a key/mouse button being pressed? 1 Answer
I want to rotate my character using analog stick. I have set up rotating towards mouse cursor 0 Answers