Character Control with Keyboard – Unity3D (C#)
I will show you 2 ways to move your character with keyboard. Create a cube named “Char” and create a script named “Movement”. You can attach this script to Char object but we won’t. Lets create an object before Start() function:
1 |
public GameObject character; |
character is a public game object which means we can reach it from Unity manually. Now, write some if statements in Update() function. This fuction is called in runtime.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
void Update () { if (Input.GetKey(KeyCode.RightArrow)){ Vector3 newPosition = character.transform.position; newPosition.x++; character.transform.position = newPosition; } if (Input.GetKey(KeyCode.LeftArrow)){ Vector3 newPosition = character.transform.position; newPosition.x--; character.transform.position = newPosition; } if (Input.GetKey(KeyCode.UpArrow)){ Vector3 newPosition = character.transform.position; newPosition.z++; character.transform.position = newPosition; } if (Input.GetKey(KeyCode.DownArrow)){ Vector3 newPosition = character.transform.position; newPosition.z--; character.transform.position -= newPosition; } } |
Now save it and back to Unity. Attach script to camera, select camera and you will see this script in inspector window. Drag Char object to Character bar in script and press play. Is it fast? Don’t worry, just a little change is needed. Back to code and add a float variable:
1 |
private float speed = 2.0f; |
and replace if statements with:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
void Update () { if (Input.GetKey(KeyCode.RightArrow)){ transform.position += Vector3.right * speed * Time.deltaTime; } if (Input.GetKey(KeyCode.LeftArrow)){ transform.position += Vector3.left* speed * Time.deltaTime; } if (Input.GetKey(KeyCode.UpArrow)){ transform.position += Vector3.forward * speed * Time.deltaTime; } if (Input.GetKey(KeyCode.DownArrow)){ transform.position += Vector3.back* speed * Time.deltaTime; } } |
Current speed is 2.0f but you can change it.
©Coffee Break Codes – Character Control with Keyboard – Unity3D (C#)
hello.
i want create a character that able run without use keyboard.
for example runner in endless.
can u help me ??
i use velocity for this job
You can use velocity to your character’s rigidbody but it should be frictionless to be endless move.().velocity = Vector2(x, y);. See Flappy Bird and Infinite Runner examples in Complete Projects for more.
GetComponent
For anyone who is not that good at programming that experience a problem with the “character” ending up going downwards/resetting or not to simply going backwards its because of a typo.
if (Input.GetKey(KeyCode.DownArrow)){
Vector3 newPosition = character.transform.position;
newPosition.z–;
character.transform.position -= newPosition;
}
Simply remove the “-” sign before “=” site before newPosition;
Nice tutorials Mocha 🙂
Say you wanted to create a 2D block like game and simply walk along the blocks. Simply add “else if” statement instead of simple “if”. This will make the script read only one of the containing scripts at a time.
This works for me
using UnityEngine;
using System.Collections;
public class playermove : MonoBehaviour {
public float speed;
private Rigidbody rb;
private Vector3 spown;
// Use this for initialization
void Start () {
rb = GetComponent ();
spown = transform.position;
}
// Update is called once per frame
void FixedUpdate () {
speed = 25;
float moveHorizontal = Input.GetAxis(“Horizontal”);
float moveVertical = Input.GetAxis(“Vertical”);
Vector3 movement = new Vector3 (moveHorizontal,0, moveVertical);
rb.AddForce (movement * speed);
}
Thanks my friend 🙂
how about i want to move my object up instead of forward?
It’s 3 dimensonal space mate, It’s Vector3.. change “x” for right-left, change “z” for forward-backward and change “y” for up-down move.. There is an icon on top-right of scene window..
So what will I change in your code to work this? sorry I don’t know what will I change 🙁 I don’t know how to use c#
Change “z” with “y”
Pingback: 11/14 Class material & assignment | DMS 231 Game and animation workshop
vegas world casino games lady luck casino caruthersville
firekeepers casino casino bonus codes
888 casino download casino slot
grand falls casino hollywood slots
online gambling for real money cashman casino slots
slot games with bonus spins vegas slots online
las vegas casinos play casino games for cash
slot games online casino slots
ipfoyl charlestown races and slots
online gambling for real money scatter slots
winstar world casino casinos near me
gambling sites liberty slots
vegas world slots charlestown races and slots
no deposit casinos best online slots
gafxcs best place to gamble in vegas
vegas casino slots posh casino online
no deposit win real cash empire casino online
scatter slots slots games
pompeii slots slots casino games
slots casino games cleopatra slots
plainridge casino liberty slots
slots online casino online
posh casino online vegas world slots
pechanga casino gsn casino
slot machines for home entertainment sugarhouse casino online
online casinos for us players online casino
cashman casino slots online casinos
play online casino pop slots
edsjbr charlestown races and slots
wizard of oz slots virgin online casino
hollywood casino posh casino online
tompow lady luck
online slot machines infinity slots
cafe casino online firekeepers casino
gsn casino games firekeepers casino
best time to play slot machines dakota sioux casino
play slots for real money no deposit win real cash
vegas casino slots zone online casino
online gambling world class casino slots
zone casino vegas world world class casino slots
heshbc online betting sites
plainridge casino quick hit slots
jackpot magic slots online casino real money
play slots online hyper casinos
pch slots slots of vegas
casinos online online slot games
vegas casino games slots of vegas casino
xclxse casino online slots
dzjpav lady luck
casinos in iowa cleopatra slots
fortune bay casino scatter slots
foxwoods online casino vegas casino games
jack online casino lady luck casino vicksburg
mqupkn slots of vegas
fortune bay casino parx online casino
xtgohc wizard of oz slots
big fish casino slots no download no registration slots
no deposit casinos best online gambling sites for real money
zone online casino slots no deposit games online for real cash
doubledown casino casino blackjack
online casino slots old vegas slots
slots lounge slot machines
pch slots tournament online casino gambling
zone online casino games no deposit casino
yeyjvs casino online slots
online casino slots vegas casino slots
mfcqfd world class casino slots
casinos online new no deposit casino usa
888 casino download vegas casino games
pop slots hollywood casino online
gold fish casino slots casino games
online casino real money best online casino
http://www.rolclub.com/debit-cards/3721123-online-lending-service.html;philippines-loan.com
I had no idea about this lol. Pretty interesting subject for sure though.
Отзывы Сотрудников О Работе, Мнения Реальных Людей
———————————–
Для различных банковских учреждений, в т.ч. Для первоначального вложения необходима сумма от 25 000 рублей, не считая стоимости приобретения инвестиционных паев. Для начала узнайте, какие на данный момент действуют условия страхования, и чем они отличаются от прошлогодних положений. И наоборот, узнайте, сколько стоит 22 500 рублей в злотах. Нет, карта «Мир» за рубежом работать не будет. Отличная карта от Сбербанка для молодежи – студенты могут предоставить только справку о стипендии, всем остальным понадобится также справка с работы. Другое название потребительского кредита – кредит на неотложные нужды Сбербанка. Банки, которые дают кредит с плохой кредитной историей и с просрочками (например, Тинькофф, русский Стандарт, Ренессанс Кредит и др.) без отказа, выбирают такое направление сотрудничества для наращивания капитала за счет повышенных процентных ставок, увеличения базы клиентов. Рецепторам. Кредит ребятами от лифта Ренессанс Кредит просто заехать и комфортно играть, если Вы раз. Все очень просто, депозиты банка Ренессанс Кредит имеет высшей уровень надежности по оценке Кредит-Рейтинг.
Перейдите ниже по ссылке, чтобы получить кредит:
http://v.ht/wCz3
Отличное время чтоб поделиться сайтом с друзьями https://mix.com/!-PfzTfQX:nat%C3%BCrlich%2C-gesund-und-fit-durchs-leben%2C-die-besten-angebote-f%C3%BCr-2019-bewertungen-zu-beliebten-produkten%2C-medikamenten.-bester-preis-%E2%9C%93-ratgeber-%E2%9C%93-erfahrungen%E2%9C%93-qualit%C3%A4t%E2%9C%93 Бонус для новых пользователей
бесплатный интернет в плей: https://texnoera.com/internet-v-polshe
dig this 3d engine
albuterol tablets
amoxicillin
https://clck.ru/FkugB –
tadalafil