- Home /
Move character using Camera Input
I'm working on one game project. It has one condition: Player should not have movement script. Camera will take keyboard input and tells player to move
I tried getting character using Gameobject in Camera script. But it didn't work.
Any suggestion is helpful!
Answer by Darkforge317 · Nov 28, 2017 at 07:56 AM
I would have to look at what you're doing to find your character in order to find out what the problem is... But putting this on your camera should work. (Make sure your character is tagged as "Player" for this script to work. I usually use tags to find my game objects)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraScript : MonoBehaviour
{
float movementSpeed = 3.0f;
GameObject player;
// Use this for initialization
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update()
{
// If we press/hold W
if (Input.GetKey(KeyCode.W))
{
// Move the player Forwards
player.transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime);
}
// Or if we press/hold S
else if (Input.GetKey(KeyCode.S))
{
// Move the player Backwards
player.transform.Translate(Vector3.back * movementSpeed * Time.deltaTime);
}
// If we press/hold A
if (Input.GetKey(KeyCode.A))
{
// Strafe the player left
player.transform.Translate(Vector3.left * movementSpeed * Time.deltaTime);
}
// Or if we press/hold D
else if (Input.GetKey(KeyCode.D))
{
// Strafe the player right
player.transform.Translate(Vector3.right * movementSpeed * Time.deltaTime);
}
}
}
Note: This script makes it so you can't press W and S at the same time, same with A and D. If you want to change this then change the "else if"s to "if"s.
The only difference will be that holding A and D or W and S will make your player stay still since you're telling the player to move opposite directions at the same time.
I hope this works for you! :)
Answer by unity_YbsbbJ6di2G_cQ · Nov 28, 2017 at 07:56 PM
This works perfect !! Thanks!
You're welcome. Please don't forget to mark my answer as the correct one...
Your answer
![](https://koobas.hobune.stream/wayback/20220612143458im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Disable Camera Movement,Stop camera movement 0 Answers
rotate Y axis to face mouse 1 Answer
Moving an object 1 Answer
Moving (teleporting) player and camera when they enter a certain area 5 Answers