Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
3
Question by DubstepDragon · Feb 09, 2014 at 12:24 PM · movetopdowntop-down

2D top-down movement...

I still cannot get around getting my movement to work as I intend.

It works fine with transform.translate, but I still need it to stop at collision, and that is what annoys me the most. So I used rigidbody2D.AddForce instead, and there are two things that I am not happy with, possibly due to my lack of knowledge about RigidBodies.

  • The first: Instead of moving at one speed, it begins slowly then starts to speed up.

  • The second: When I let go of the key, it does not stop...

Here is my code sample:

 using UnityEngine;
 using System.Collections;
 
 public class Move : MonoBehaviour {
 
     public float speed;
 
     void Update() {
         if(Input.GetKey(KeyCode.W)) {
             rigidbody2D.AddForce(Vector2.up * speed);
         }
 
         if(Input.GetKey(KeyCode.A)) {
             rigidbody2D.AddForce(-Vector2.right * speed);
         }
 
         if(Input.GetKey(KeyCode.S)) {
             rigidbody2D.AddForce(-Vector2.up * speed);
         }
 
         if(Input.GetKey(KeyCode.D)) {
             rigidbody2D.AddForce(Vector2.right * speed);
         }
     }
 }


Thank you so much for your assistance, this has been such a great community so far and I am very pleased with the excellent assistance :D

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Veljko023 · Dec 30, 2015 at 07:16 PM 0
Share

Why don't you just add an if statement that if you let the key go that it adds force to the opposite direction?

6 Replies

· Add your reply
  • Sort: 
avatar image
5
Best Answer

Answer by Flint Silver · Feb 09, 2014 at 03:06 PM

I'm doing a Top-Down too, and one of the best Top-Down movements script I've done is this:

 public class PlayerMovements : MonoBehaviour{
 // Normal Movements Variables
     private float walkSpeed;
     private float curSpeed;
     private float maxSpeed;
 
     private CharacterStat plStat;
 
     void Start()
     {
         plStat = GetComponent<CharacterStat>();
 
         walkSpeed = (float)(plStat.Speed + (plStat.Agility/5));
         sprintSpeed = walkSpeed + (walkSpeed / 2);
 
     }
 
     void FixedUpdate()
     {
         curSpeed = walkSpeed;
         maxSpeed = curSpeed;
 
         // Move senteces
           rigidbody2D.velocity = new Vector2(Mathf.Lerp(0, Input.GetAxis("Horizontal")* curSpeed, 0.8f),
                                                Mathf.Lerp(0, Input.GetAxis("Vertical")* curSpeed, 0.8f));
 }
 }

 

Hope It will be Helpful! :)

Sorry for my Bad English :oops:

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image DubstepDragon · Feb 17, 2014 at 08:41 PM 1
Share

Thanks bro! :D Oh and I don't have anything against bad English... although your English was alright to begin with, you needn't apologize :D

avatar image Flint Silver · Feb 26, 2014 at 05:31 PM 0
Share

thank you man :) (Don't remove $$anonymous$$athf.Lerp and don't give a velocity over 8 ( more less, I don't remember well ) because it will be a bug when the gameObject change direction )

avatar image sicorax22 · Apr 30, 2015 at 05:50 AM 0
Share

Why do you have three variables, walkSpeed, curSpeed and maxSpeed in this code when you seem to just set them all to the same value during FixedUpdate anyway? It seems redundant. Why not just have the variable walkSpeed?

avatar image itaisinger · Jul 23, 2017 at 12:46 PM 1
Share

hi. im very new to this so it might be a dumb problem, but some of the code i copied from here gives me error. it might be because this is pretty old and c# or unity changed. anyway, what should i switch ""private CharacterStat plStat;" with? no idea what this is supposed to do.

avatar image gmak itaisinger · May 13, 2019 at 12:38 AM 0
Share

2 years late, but for other readers, you need to create a scrip called CharacterStat which contains Speed & agility, and add it as a component. sprintSpeed is undefined though, but as its name implies, could be used to sprint; you'd have to add the code for it. As is, can simple be commented.

avatar image
4

Answer by oOoJaMz93oOo · Jun 06, 2014 at 10:49 PM

 #pragma strict
 
 
 
 //Inspector Variables
 var playerSpeed : float = 10; //speed player moves
 var turnSpeed : float = 100; // speed player turns
 
 function Update () 
 {
 
     MoveForward(); // Player Movement
     TurnRightAndLeft();//Player Turning
 }
 
 function MoveForward()
 {
 
     if(Input.GetKey("up"))//Press up arrow key to move forward on the Y AXIS
     {
         transform.Translate(0,playerSpeed * Time.deltaTime,0);
     }
 
 }
 
 function TurnRightAndLeft()
 {
 
     if(Input.GetKey("right")) //Right arrow key to turn right
     {
         transform.Rotate(-Vector3.forward *turnSpeed* Time.deltaTime);
     }
 
     if(Input.GetKey("left"))//Left arrow key to turn left
     {
         transform.Rotate(Vector3.forward *turnSpeed* Time.deltaTime);
     }
 
 }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ChuggyC · Oct 25, 2015 at 12:11 PM 0
Share

Thanks, this is exactly what I have been trying to figure out. : )

avatar image
2

Answer by Headworker · Feb 09, 2014 at 01:55 PM

I think i can help you:

1) The first thing I would do is to collect all input from one frame and apply it as a whole like this :

 Vector2 AxisInput;
 public float Speed;
 
 void Update()
 {
     Vector2 AxisInput = (new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")));
 
     rigidbody.AddForce(AxisInput*Speed, ForceMode.VelocityChange ); // For ForceMode see 2)
    
 }

2) Your rigidbody is acclerating slowly because of inertia. This can be changed in 2 ways:

  • Choose another ForceMode in the AddForce call (like velocity change demonstrated earlier)

  • (recommended) You can make this like you want via tinkering with mass/drag/angular drag. This will also solve your second problem (movement not stopping after input change)

  • I can't guarantee these values to fit instantly but my rigidbody worked at this values:

rigidbody mass: ~45

rigidbody drag: 5

rigidbody angular drag: 5 // wont be needed in you case, used for rotation force resistance.

force used in Addforce was 150 (multiplied by axisinput) tinker with the values and it will work soon!

As always, if you have any questions left, just ask!

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image DajBuzi · Feb 09, 2014 at 09:05 PM 0
Share

If you're using built in physics it is recommended to useFixedUpdate ins$$anonymous$$d Update.

Great and detailed answer.

avatar image Headworker · Feb 15, 2014 at 11:52 AM 0
Share

I could be wrong, but when using the Update() function, my Input reactions felt much smoother.

avatar image
2

Answer by APenguin · Feb 09, 2014 at 01:59 PM

You wouldn't need to use rigidbody2D.AddForce to create collision. If you just make your player a rigidbody, and add a collider to the player, use a box collider or capsule collider, and also add a collider to the object you want to collide then when the player runs into the object the player should collide with it.

You can keep it as transform.translate. There shouldn't be any problems with what i have suggested you to do. If there is, post them up and i will try and help.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by DajBuzi · Feb 09, 2014 at 03:06 PM

Use rigidbody2D.velocity Like so: rigidbody2D.velocity =new Vector2(Input.GetAxis("Horizontal") * speedValue, Input.GetAxis("Vertical") *speedValue);

If thats not enough for your question then i'll add more details to this.

PS. sorry for typos and unformatted code,dont know how to do this onmobile device.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
  • 1
  • 2
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

29 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

A node in a childnode? 1 Answer

Top-down movement in 2D 1 Answer

MoveTowards problem 1 Answer

Inventory system using an array... 3 Answers

I've to refresh script's folder in Unity 3.1, Why? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges