How to transform position to left?
So, I'm basically trying to move an object from the right side to the left side. I'm trying this code but every time I run the game, after a certain point it starts to somehow to subtract way more than what the code says. Even before reaching the negative axis. Could someone help me please?
using UnityEngine;
using System.Collections;
public class GroupMovement : MonoBehaviour
{
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
InvokeRepeating("moveR", 1, 1);
StartCoroutine(Wait());
}
public void moveR()
{
transform.position = new Vector2(rb.position.x + 1, rb.position.y);
}
public void moveL()
{
transform.position = new Vector2(rb.position.x - 1, rb.position.y);
}
void Update() {
}
public void CancelR()
{
CancelInvoke("moveR");
Wait();
}
public void CancelL()
{
CancelInvoke("moveL");
Wait();
}
void moveDown()
{
transform.position = new Vector2(rb.position.x, rb.position.y - 1);
}
IEnumerator Wait()
{
yield return new WaitForSeconds(1);
Debug.Log("Wait");
}
}
Answer by Kishotta · Feb 17, 2018 at 04:38 PM
You have a lot of code here that doesn't appear to be doing anything. If you're just needing your object to move to the left (and want to use coroutines), you could try something like:
private IEnumerator MoveLeft (float moveAmount, float waitTime) {
// Move left forever, could just as easily check for a certain bound like:
// while (transform.position.x < -10.0f) {
while (true) {
transform.position += Vector3.left * moveAmount;
yield return new WaitForSeconds (waitTime);
}
// Will return and stop if/when condition is met
}
You can invoke the coroutine in Start
or Awake
using:
StartCoroutine (MoveLeft (1.0f, 1.0f));
Ok, I'll try using this one. Thanks for the help.
Your answer
Follow this Question
Related Questions
how do i make player die when falling certain height? 3 Answers
How does physics work in this code? 0 Answers
Make object move back and forth 2 Answers
Enemy attack radius 4 Answers
How to add random force on x axis for a moving object? 0 Answers