1,transform.positionを使う。
//始めの位置を指定する。
this.gameObject.transform.position = new Vector3(0f, 0f, 0f);
またUpdateメソッド内で少しづつ位置を変えることで移動させられる。
:Vector3は構造体(値型)であるので、現在の値を代入したposをもう一度transform.positionに渡す必要がある。
void Update()
{
//現在の位置を取得
Vector3 pos = this.gameObject.transform.position;
//現在の位置からx方向に1移動する
this.gameObject.transform.position = new Vector3(pos.x + 1, pos.y, pos.z);
}
2.transform.Translateを使う。
void Update()
{
// 毎秒その物体のZ軸方向に+1進む
transform.Translate(Vector3.forward * Time.deltaTime);
// 毎秒ワールドのX軸方向に+1進む
transform.Translate(Time.deltaTime, 0f, 0f, Space.World);
}
3.AddForceを使う
FixedUpdateは物理量の計算をするときに用いる。
デフォルトでForceMode.Forceとなるので省略できる。
void FixedUpdate()
{
rb.AddForce(0f,2f,0f,ForceMode.Force);
}
}
ForceMode | 詳細 |
---|---|
Force | 一定に力を加え続ける。質量は考慮される |
Acceleration | 加速され続ける。 質量は無視される。 |
Impulse | 瞬間に力を加える(爆発のような)質量は考慮される。 |
VelocityChange | 瞬間にその速度になるように力を加える。質量は無視される。 |
4.MovePositionを使う
MovePositionはRigidbodiがKinematicでも働き滑らかに動く。
Dynamicの時は滑らかよりtransform.position = new posに近くなるので注意
//rb はRigidbodyの型でRigidbodyをGetComponentしている
rb.MovePosition(transform.position + Vector3.forward * Time.deltaTime);
急に移動して衝突判定をすり抜けたくない時に滑らかに動くので役に立つ。