How to push player left and right
I need my player to go always forward and i want it to swing in opposite directions every time on click. It should be like on this game but in 3D https://www.youtube.com/watch?v=rFeoRlH_0ek
Answer by E_101 · Jan 23, 2018 at 05:29 PM
Although this is made for Unity 2D it should not be too far a stretch to convert into 3D. Using this code we can force the player to constantly be going downwards, also allowing the player to use any key you decide on to swing them left and right. It will also check for you the rotation so that the player can not over swing, which you will have to tinker with to your liking. Some of the code will certainly have to be edited to fit you're liking, as well as turn it into 3D. Hopefully it will be sufficient. Where it says transform.position -= transform.up * Time.deltaTime * speed;
That is where you change transform.up to transform.forward to work in unity 3D.
using UnityEngine;
using System.Collections;
public class movement : MonoBehaviour
{
public Rigidbody2D playerOne;
public int speed;
public KeyCode leftKey;
public KeyCode rightKey;
public Vector2 towardsPoint;
public int rotateSpeed;
// Use this for initialization
void Start ()
{
playerOne.velocity = towardsPoint * 10;
}
// Update is called once per frame
void Update ()
{
if (Input.GetKey (leftKey) && playerOne.transform.rotation.eulerAngles.z <= 90) {
transform.Rotate (0, 0, rotateSpeed * Time.deltaTime, Space.World);
transform.position -= transform.up * Time.deltaTime * speed;
}
if (Input.GetKey (rightKey) && playerOne.transform.rotation.eulerAngles.z <= 90) {
transform.Rotate (0, 0, -rotateSpeed *Time.deltaTime, Space.World);
transform.position -= transform.up * Time.deltaTime * speed;
}
}
}
Other Unity User's Questions that Helped Figure This One Out
Move in Direction Facing https://answers.unity.com/questions/616195/how-to-make-an-object-go-the-direction-it-is-facin.html
Don't Overturn https://answers.unity.com/questions/254798/check-an-objects-rotation.html
Constant Speed https://answers.unity.com/questions/704483/moving-object-at-constant-speed.html
Constant Speed 2 https://gamedev.stackexchange.com/questions/101025/moving-a-character-depending-on-the-direction-he-is-facing-c-unity3d
Hopefully this has at least helped a little and someone will come along and make this even easier as I am a novice to 3D and 2D Unity.
Your answer
Follow this Question
Related Questions
Issue with wave-like motion when rotating with mouse input 0 Answers
Buttons for Player movement 0 Answers
Character Diagonal Movement Issue 3 Answers
Switching lanes 1 Answer
Rotating object towards (0,0,0) during idle (no input) 0 Answers