- Home /
Moving an Object - The right way. 2D
Hello everyone, hope you're doing good!
So, I came across a problem of mine. I wanted to addForce to an Object. Here's the Question:
Now, I did a Debug.Log on the ball's velocity when it's moving but I found out it was (0,0)
So my question is this, is this the best way to move an object?
The idea is that the gameObject(Ball) goes towards the player when inRadius.
Here's how Im moving:
void Update (){
transform.position = Vector3.MoveTowards(transform.position, playerPos, moveSpeed * Time.deltaTime);
if (transform.position == playerPos) {
GetPlayerPos();
}
if (Time.time - _startTimer >= 5) {
GetPlayerPos();
}
}
So, timer is there so It doesn't constantly get the same position over and over.
GetPlayerPos does this:
public void GetPlayerPos (){
playerPos = GameObject.Find ("Player").transform.position;
_startTimer = Time.time;
}
Now 2 quick questions:
1)Am I moving my object the best way towards my player?(I want to be able to use physics and such...) 2)If Im doing this the right way, why does the object don't have any velocity?
Thank you for your time!!!
Answer by Kiwasi · Dec 01, 2014 at 05:33 PM
The right way to move an object with physics is RigidBody.AddForce or RigidBody.velocity.
Using transform.position causes an object to 'teleport' and will override any physics you use.
@Bored$$anonymous$$ormon
So, in this particular case how would you translate movetowards to velocity?( rigidbody.velocity = desiredPosition; ??
@Bored$$anonymous$$ormon
Ok , I tried this:
this.rigidbody2D.velocity = Vector3.$$anonymous$$oveTowards(transform.position, playerPos, moveSpeed * Time.deltaTime);
The object moves towards another way haha. ;/ I think I did this totally wrong. haha
@Bored$$anonymous$$ormon
Ok, I did some research , rigidBody2D.movePosition(vector2) will move towards that position so what I did was this: float tempY = transform.position.y; float tempX = transform.position.x; Vector2 tempPosit = new Vector2(tempX - 0.1f,tempY); //transform.position = Vector2.$$anonymous$$oveTowards(transform.position, tempPosit, speed * Time.deltaTime); rigidbody2D.$$anonymous$$ovePosition(tempPosit);
But the object isnt moving :/
Your answer
Follow this Question
Related Questions
How to smooth movement object in one-axis? 1 Answer
2D Background Stop Moving on BoundingBox Exit? 2 Answers
Setting target position in Vector3.MoveTowards 2 Answers
Input.mousePosition returns coordinates as integers. 1 Answer
Lerp not working 1 Answer