Problems With Walking Code
So I'm pretty new to C#. I coded this, and while it does work for the most part, there are two problems: First, I have to repeatedly tap the directions to make the player move continuously. Second, whenever I press W or S, it moves forward or backward at the angle of the camera, instead of staying on the floor. (The game this is for doesn't have any parts that the player's elevation changes, if that helps) This is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class walk : MonoBehaviour {
public float speed = 100;
private Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("a"))
{
transform.Translate(Vector3.left * speed * Time.deltaTime);
}
if (Input.GetKeyDown("d"))
{
transform.Translate(Vector3.right * speed * Time.deltaTime);
}
if (Input.GetKeyDown("w"))
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
if (Input.GetKeyDown("s"))
{
transform.Translate(Vector3.back * speed * Time.deltaTime);
}
}
}
Answer by Hellium · Sep 10, 2020 at 06:42 PM
public float speed = 100;
// Update is called once per frame
void Update()
{
if (Input.GetKey("a"))
{
Translate(Vector3.left);
}
if (Input.GetKey("d"))
{
Translate(Vector3.right);
}
if (Input.GetKey("w"))
{
Translate(Vector3.forward);
}
if (Input.GetKey("s"))
{
Translate(Vector3.back);
}
}
private void Translate(Vector3 direction)
{
direction = transform.TransformDirection(direction);
direction = Vector3.ProjectOnPlane(direction, Vector3.up).normalized;
transform.Translate(direction * Time.deltaTime * speed, Space.World);
}
Hey so I put in what you were suggesting, and while I did have to do a little cleaning up, I have a problem I can't solve:
private void Translate(Vector3 direction)
{
transform.TransformDirection(direction);
direction = Vector3.ProjectOnPlane(direction, Vector3.up).normalized;
Vector3 speed = default;
Transform.Translate(Vector3.direction, Time.deltaTime, speed, Space.World);
}
}
In the last line, it gives me an error with the "direction". It says: "'Vector3' does not contain a definition for 'direction.'" Any idea how I could fix this?
Oh shoot, thank you so much for your help, I'll go ahead and fix it.
Your answer
Follow this Question
Related Questions
How to move a game object to a position after selecting it 0 Answers
How to SHOOT an object on a curved path without using Rigidbody 2 Answers
Check whether a group of instantiated 2D rigid bodies are moving 1 Answer
Player not moving in the right direction instantly 1 Answer
Instantiated Prefab not Moving 1 Answer