Reputation: 35
Ive been trying to make this Object move forward on its own and turn left or right in circular fashion if the left/right keys are pressed with unity using C#, this picture will make it clearer: http://prnt.sc/avmxbn
I was only able to make it move on its own and this is my code so far:
using UnityEngine;
using System.Collections;
public class PlayerBehaviour : MonoBehaviour {
Update(){ transform.localPosition += transform.forward *speed *Time.deltaTime
float speed = 5.0f;
// Use this for initialization
void Start () {
Debug.Log ("it's working?");
}
// Update is called once per frame
void Update () {
transform.localPosition += transform.forward * speed * Time.deltaTime;
}
void FixedUpdate(){
}
}
I have no idea, however, how to change left or right directions in circular paths like the picture linked demonstrates. Anyone able to help me? Thank you.
Upvotes: 0
Views: 1917
Reputation: 146
You can use this script for movement :
using UnityEngine;
public class MovementController : MonoBehaviour {
public Rigidbody rigidbody;
float angle = 0f;
const float SPEED = 1f;
float multiplier = 1f;
void FixedUpdate(){
if ( Input.GetKey (KeyCode.LeftArrow) )
angle -= Time.deltaTime * SPEED * multiplier;
else if( Input.GetKey (KeyCode.RightArrow) )
angle += Time.deltaTime * SPEED * multiplier;
rigidbody.velocity = new Vector2(Mathf.Sin(angle) * SPEED, Mathf.Cos(angle) * SPEED);
}
}
Multiplier value is inversely proportional to the radius.
Upvotes: 0
Reputation: 722
Attach this script to your moving object:
using UnityEngine;
public class MoveController : MonoBehaviour {
float angle = 1F;
float speed = 0.2F;
void Update ()
{
if ( Input.GetKey (KeyCode.LeftArrow) )
transform.Rotate(Vector3.up, -angle);
else if( Input.GetKey (KeyCode.RightArrow) )
transform.Rotate(Vector3.up, angle);
transform.Translate(Vector3.forward * speed);
}
}
The key point here is to separate your moving from your rotating functionality.
Upvotes: 0
Reputation: 2031
There are obvious errors in your code. You call Update()
twice. The first time without a return type. You shouldn't do that. Start by deleting the first Update()
and the code on the same line.
Then to answer your question you will have to look into getting input from the user. Use Input.GetKey()
and pass it a KeyCode
value such as KeyCode.A
for the 'A' key. So you can say:
if(Input.GetKey(KeyCode.A))
{
//do something(for example, Turn the player right.)
}
Then look into rotating the object using transform.Roate
to rotate the player.
Upvotes: 1