- Home /
How do I move a 2d object to center of screen?
public float fallSpeed = 100.0f;
void Update()
{
transform.Translate(Vector3.down * fallSpeed * Time.deltaTime);
}
I currently have this code making my object fall down and it goes off the camera screen, I then want it to move to the center of the screen to which then it will activate a particle explosion. How would I go about doing that?
Answer by Cherno · Jun 27, 2015 at 12:06 AM
You can use Camera.ViewportToWorldPoint and pass it a Vector3 with x and y values = 0.5 (middle of viewport). The z values would determine the distance from the camera.
thanks, is there a way i could speak to you more about this? a little confused on how to make this translate in code.
Let's say you have a GameObject go that you want to put in the center of the screen.
public GameObject go;
float distanceFromCamera = 10f;
void Start() {
Vector3 centerPos = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, distanceFromCamera));
go.transform.position = centerPos;
}
ah ok, awesome thanks! Now how would i go about activating the particle portion?
Does the object already have a ParticleSystem? If yes,set it to Play on Awake = true, and deactivate the ParticleSystem component. Then, after centering the gameobject, enable it by code:
go.GetComponent<ParticleSystem>().enableD = true;
Or, you could set it to Play on Awake = false, and use ParticleSystem.Emit to emit particles after centering the gameobject.
go.GetComponent<ParticleSystem>().emit(20);
i created the particle, and its checked to play on awake in the inspector. I should uncheck this before coding it in you mean?
Your answer
Follow this Question
Related Questions
2D Platformer Pick up and move object script help! 1 Answer
Best Image Formats, Sizes, and Resolutions for Unity Sprites? 2 Answers
Unity doesn't open mi project 0 Answers
How can I create force on one end of an object using mouse dragg whose other end is fixed 1 Answer
waypoint stuck at the first waypoint 3 Answers