- Home /
Question by
Essexrookie · Sep 07, 2019 at 02:32 PM ·
c#camera2d
How to move object side to side of screen width
Hello, I looked up a solution to move an object side to side horizontally.
public float delta = 1.5f;
public float speed = 2.0f;
private Vector3 startPos;
void Start()
{
startPos = transform.position;
}
void Update()
{
Vector3 v = startPos;
v.x += delta * Mathf.Sin(Time.time * speed);
transform.position = v;
}
but instead of having a value "delta" I would rather it just move from the left side of the camera to the right side of the camera back & forth matter the size. How to accomplish this?
Comment
hello, would I suggest a complete different approximation of the solution?
public float speed = 2.0f;
bool back = false; //check if movement is backwards or forwards
Vector3 destination; //objective Position, the position that current instance want to reach, on camera space (viewed from the camera)
Vector3 Space3dDestination;
private Vector3 startPos;
void Start()
{
startPos = transform.position;
}
void Update()
{
//construct the destination, you can calculate y and z on start to optimize
//same pos of startpoint on y axis
destination.y = Camera.main.WorldToScreenPoint(transform.position).y;
//z is always the distance between camera and the point
destination.z = Vector3.Distance(Camera.main.transform.position, startPos);
//x depends where is this instance going
if(back)
destination.x = Camera.main.pixelWidth; //move left
else
destination.x = 0f; //move right
//point on 3d Space
Space3dDestination = cam.ScreenToWorldPoint(destination);
//move transform
transform.position = Vector3.$$anonymous$$oveTowards(transform.position, Space3dDestination, (Time.deltaTime * speed));
//check if is close to destination, and change movement
if((transform.position - Space3dDestination).sqr$$anonymous$$agnitude < .1f){
back = !back;
}
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Change the background color attribute of a camera in C#? 2 Answers
Screen Points to construct a Rect (Not axis aligned) 0 Answers
Why is Input.mousePosition returning wired values using Cinemachine 2D with dynamic following? 0 Answers
Stop 2D camera X axis movement if equal to one of two coordinates 1 Answer