Moving object alone y-axis
I have look at other posts but I'm still confused as to how to do it I want to move these bricks in a breakout game from position 3 to 2 and back and forth, starting from y-position 3. I have never learned C# before and I'm just building with codes I got different places. Here are my codes:
using UnityEngine; using System.Collections;
public class MoveBricks : MonoBehaviour {
void Update()
{
var vel = GetComponent<Rigidbody2D>().velocity;
var pos = GetComponent<Rigidbody2D>().position;
GetComponent<Rigidbody2D>().position = pos;
if (pos.y >= 3)
{
vel.y = -.5f;
GetComponent<Rigidbody2D>().velocity = vel;
}
if (pos.y >= 2f && pos.y <= 3)
{
GetComponent<Rigidbody2D>().velocity = vel;
}
if (pos.y <= 2f)
{
vel.y = .5f;
GetComponent<Rigidbody2D>().velocity = vel;
}
}
}
These codes move my brick from 3 to around 4.6 then to 3.6 and back and forth from there. Why?
Answer by cjdev · Feb 05, 2016 at 07:42 AM
The reason is you're using Rigidbodys and their velocities. They are physics objects and have other forces acting on them like inertia and drag. Rather than the 'go here, stop, and do this' kind of mentality of a typical coding process they have the more physically-based properties of 'for every action there is an equal and opposite reaction'. The bottom line for your purposes is that, assuming you don't want to wrestle with the physics, you want to manipulate the GameObject's transform directly instead. Something like this:
transform.position += Vector2.right * Time.deltaTime;
Putting that in the update loop will move your block at one unit per second to the right. This kind of position manipulation is a lot easier than trying to fly around like a spaceship in my opinion.
I don't fully understand how that line is suppose to work. All it did was move my bricks to (0, 0) and move it to the whatever Vector.2(x, y) and back once then it starts twitching. Sometimes it will move it have way then go back to (0, 0). Is this because it is updating too fast or that one second time frame is too short? Even if it's not, how can can change the time frame? It also wouldn't let me use += on Vectors
Also How can I have it so it doesn't start at (0, 0) ? Should I change the positions using Start and then transform? Or can I set transform.position equal to a position?
Your answer
Follow this Question
Related Questions
[SOLVED]My OnMuseDown execute only once 1 Answer
First person shooter : Leaning! 2 Answers
NavMesh of an automatically generated maze 0 Answers
How can I fix this script or make one similar? 1 Answer
Menu object not responding 0 Answers