I'm making a 2D game and trying to make a characters move automatically when they spawn from the door to the desk or close to the sofa then stop there. the problem is that they don't collide with anything in the background like sofa or table or desk and they keep going trying to force move and going out of the canvas. this is a GIF for the game play and script that i'm using on the characters:
What am I supposed to do?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterConstantMove : MonoBehaviour
{
GameManager Game_Manager;
void Start()
{
GameObject gameController = GameObject.FindGameObjectWithTag("GameController");
Game_Manager = gameController.GetComponent<GameManager>();
}
void Update()
{
transform.Translate(Game_Manager.moveVector * Game_Manager.moveSpeed * Time.deltaTime);
}
}
GameManager.Cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public float moveSpeed = 1.0f;
public Vector2 moveVector;
}
CodePudding user response:
That's what happens when you translate the body in every frame. From an answer to this similar problem has been addressed, Transform
is not a physics-based component. It's the position, rotation, and scale of the object. It doesn't interact with physics system on it's own. Rigidbody
is a physics-based component that performs different kinds of physics interactions, like collisions, forces, and more.
Add a rigidbody component to your gameobject and set its velocity, it then interacts with the game physics.
private Rigidbody2D rb;
private void Awake() {
rb = GetComponent<Rigidbody2D>();
}
private void Update() {
rb.velocity = Game_Manager.moveVector * Game_Manager.moveSpeed;
}