- Home /
How to make players follow only the movement but not the position / vector.
First of all, sorry for my English.
I am now doing 2d top down game. I want when I move my player to the up/down or left/ right, another gameObject will follow even it is not in a same position / vector. At the same time it was in the mirror movement. I mean when I move right, it will move to the left. But if I get stuck on some collider but still pressing forward button, that gameObject will still moving forward if there is no collider in front of him.
Here is the code I use and work perfectly in mirror effect movement. But I cannot achieve what I want using this code. I want to know:
1) How can I make the gameObject still moving forward (no collider in front of him) when I pressed forward button even if I stuck on some collider.
2) How can I stop the gameobject from going through the wall?
using UnityEngine;
using System.Collections;
public class Mirror : MonoBehaviour {
public GameObject mirrorObject; // Object to mirror
public bool mirrorX; // Wether or not to mirror the X axis
public bool mirrorY; // Wether or not to mirror the Y axis
public bool mirrorZ; // Wether or not to mirror the Z axis
public bool useLateUpdate; // Wether or not to set the object's position in LateUpdate
void Update()
{
Vector3 newPosition;
newPosition = mirrorObject.transform.position; // Get the mirrorObject's position
if(mirrorX)
{
newPosition.x = -newPosition.x; // Mirror on the X axis
}
if(mirrorY)
{
newPosition.y = -newPosition.y; // Mirror on the Y axis
}
if(mirrorZ)
{
newPosition.y = -newPosition.y; // Mirror on the Z axis
}
if(!useLateUpdate)
transform.position = newPosition; // Set object's position equal to the new mirrored position
}
void LateUpdate()
{
if(useLateUpdate)
transform.position = newPosition; // Set object's position equal to the new mirrored position
}
}
Not sure if I understand correctly but, maybe you should try movement using AddForce() and a max speed variable, along with high friction physics materials to avoid any inertia
Something like:
public float moveForce;
...
float hInput = Input.GetAxis ("Horizontal");
//If the player is changing directions or hasn't reached the maximum velocity
if (hInput * rigidbody2D.velocity.x < maxVelocity)
//...add force to the player in the "hInput" direction
rigidbody2D.AddForce (Vector2.right * hInput * moveForce);
The same through Input.GetAxis ("Vertical"); and Vector2.up for vertical movement
Then applying the script to the two objects you want to move.
$$anonymous$$ind of like controlling two players at the same time, ins$$anonymous$$d of mirroring their movements.