Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 /
  • Help Room /
avatar image
0
Question by CadenGS_ · May 09, 2018 at 05:19 AM · movementunity 2d2d-platformerattack

Help 2D attack

I'm making a 2D platform fighter but I've looked all over the internet and I'm not sure i can find what I'm looking for. I'm trying to make a melee attack to when you hit R-click on the mouse it dashes in the direction you are walking.

Ill try and figure out knock-back or dmg later. Any help with the movement of the script?

I'll list my current movement ode below.

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 namespace NinjaController {
 
   [RequireComponent(typeof(Rigidbody2D))]
   [RequireComponent(typeof(Collider2D))]
   public class NinjaController : MonoBehaviour {
 
     private Rigidbody2D RBody { get; set; }
 
     [SerializeField]
     private PhysicsParams physicsParams;
 
     public Vector2 Velocity { get { return(RBody.velocity); } }
 
     public Vector2 VelocityRelativeGround { get { return(Velocity / PhysicsParams.onGroundMaxVelHorizontal); } }
 
     private float timeRealLastGroundCollision = 0;
     private float timeRealLastWallLeftCollision = 0;
     private float timeRealLastWallRightCollision = 0;
 
     public bool IsOnGround {
       get {
         return GetIsColliding(timeRealLastGroundCollision);
       }
     }
 
     public bool IsOnWallLeft {
       get {
         return GetIsColliding(timeRealLastWallLeftCollision);
       }
     }
 
     public bool IsOnWallRight {
       get {
         return GetIsColliding(timeRealLastWallRightCollision);
       }
     }
 
     public bool IsInAir { get { return isPlayerInAir; } }
 
     private bool GetIsColliding(float timeLastCollision) {
       return(Time.realtimeSinceStartup < timeLastCollision + 0.05f);
     }
 
     private Vector2 currentVelocity = Vector2.zero;
     private Vector2 currentForce = Vector2.zero;
 
     private float EntityMass { get { return(PhysicsParams.playerMass); } }
 
     private bool isPlayerInAir = false;
     private bool keyJumpRetrigger = false;
     private bool keyJumpPressed = false;
     private bool isPlayerOnWall = false;
 
     public PhysicsParams PhysicsParams {
       get { return physicsParams; }
       set { physicsParams = value; }
     }
 
     public Vector2 CurrentForce { get { return currentForce; } }
 
     public bool IsOnWall { get { return isPlayerOnWall; } }
 
     private List<Renderer> allRenderers;
 
     public List<Renderer> AllRenderers { get { return allRenderers; } }
 
     public Vector3 Position {
       get {
         return transform.position;
       }
       set {
         transform.position = value;
       }
     }
 
     public Vector2 Position2D {
       get {
         return transform.position;
       }
       set {
         transform.position = value;
       }
     }
 
     public void Awake() {
       RBody = GetComponent<Rigidbody2D>();
       allRenderers = new List<Renderer>(GetComponentsInChildren<Renderer>(true));
     }
       
     public void Update() {
 
       //let's reset forces to 0 and then add regular gravitation
       SimResetForce();
       SimAddForce(new Vector2(0, PhysicsParams.gameGravity) * EntityMass);
 
       //process key input (like jumping key pressed, etc...)
       ProcessInput();
 
       //simulate position and velocity based on all acting forces
       ComputeVelocity(Time.deltaTime);
 
       //collision detection with static world
       isPlayerOnWall = IsOnWallLeft || IsOnWallRight;
       isPlayerInAir = IsOnGround == false;
     }
 
     private void SimResetForce() {
       currentForce = Vector2.zero;
     }
 
     private void SimAddForce(Vector2 force) {
       currentForce += force;
     }
 
     private void ComputeVelocity(float dt) {
 
       currentVelocity += (currentForce / EntityMass) * dt;
 
       //let's cap the speed in case its higher than the max
       if (isPlayerInAir) {
         currentVelocity.x = Mathf.Clamp(currentVelocity.x, -PhysicsParams.inAirMaxVelHorizontal, PhysicsParams.inAirMaxVelHorizontal);
       } else {
         currentVelocity.x = Mathf.Clamp(currentVelocity.x, -PhysicsParams.onGroundMaxVelHorizontal, PhysicsParams.onGroundMaxVelHorizontal);
       }
 
       RBody.velocity = currentVelocity;
     }
 
     private void ProcessInput() {
 
       bool isKeyDownJump = Input.GetButton("Jump");
       float inputAxisX = Input.GetAxisRaw("Horizontal");
       bool isKeyDownLeft = inputAxisX < -0.5f;
       bool isKeyDownRight = inputAxisX > 0.5f;
 
       //-----------------
       //JUMPING LOGIC:
       //player is on ground
       if (isPlayerInAir == false) {
         //in case the player is on ground and does not press the jump key, he
         //should be allowed to jump
         if (isKeyDownJump == false) {
           keyJumpRetrigger = true;
         }
 
         //did player press down the jump button?
         if (isKeyDownJump == true && keyJumpRetrigger == true) {
           keyJumpPressed = true;
           keyJumpRetrigger = false;
 
           //when pressing jump on ground we set the upwards velocity directly
           currentVelocity = new Vector2(currentVelocity.x, PhysicsParams.jumpUpVel);
         }
       } else if (isPlayerOnWall == true) {
         //let's allow jumping again in case of being on the wall
         if (isKeyDownJump == false) {
           keyJumpRetrigger = true;
         }
         if (currentVelocity.y < 0) {//apply friction when moving downwards
           SimAddForce(new Vector2(0, PhysicsParams.wallFriction) * EntityMass);
         }
         if (currentVelocity.y < PhysicsParams.wallFrictionStrongVelThreshold) {//apply even more friction when moving downwards fast
           SimAddForce(new Vector2(0, PhysicsParams.wallFrictionStrong) * EntityMass);
         }
         if (isKeyDownJump == true && keyJumpRetrigger == true) {
           keyJumpPressed = true;
           keyJumpRetrigger = false;
 
           //in case we are moving down -> let's set the velocity directly
           //in case we are moving up -> sum up velocity
           if (IsOnWallLeft == true) {
             if (currentVelocity.y <= 0) {
               currentVelocity = new Vector2(PhysicsParams.jumpWallVelHorizontal, PhysicsParams.jumpWallVelVertical);
             } else {
               currentVelocity = new Vector2(PhysicsParams.jumpWallVelHorizontal, currentVelocity.y + PhysicsParams.jumpWallVelVertical);
             }
           } else if (IsOnWallRight == true) {
             if (currentVelocity.y <= 0)
               currentVelocity = new Vector2(-PhysicsParams.jumpWallVelHorizontal, PhysicsParams.jumpWallVelVertical);
             else
               currentVelocity = new Vector2(-PhysicsParams.jumpWallVelHorizontal, currentVelocity.y + PhysicsParams.jumpWallVelVertical);
           }
         }
       }
       //did player lift the jump button?
       if (isKeyDownJump == false) {
         keyJumpPressed = false;
       }
 
       //let's apply force in case we are holding the jump key during a jump.
       if (keyJumpPressed == true) {
         SimAddForce(new Vector2(0, PhysicsParams.jumpUpForce) * EntityMass);
       }
       //however let's stop doing that as soon as we fall down after the up-phase.
       if (keyJumpPressed == true && currentVelocity.y <= 0) {
         keyJumpPressed = false;
       }
 
       //let's apply additional gravity in case we're in air moving up but not holding the jump button
       if (keyJumpPressed == false && isPlayerInAir == true && currentVelocity.y > 0) {
         SimAddForce(new Vector2(0, PhysicsParams.jumpGravity) * EntityMass);
       }
 
       //-----------------
       //IN AIR SIDEWAYS:
       if (isPlayerInAir == true) {
         //steering into moving direction (slow accel)
         if (isKeyDownLeft == true && currentVelocity.x <= 0)
           SimAddForce(new Vector2(-PhysicsParams.inAirMoveHorizontalForce, 0) * EntityMass);
         else if (isKeyDownRight == true && currentVelocity.x >= 0)
           SimAddForce(new Vector2(PhysicsParams.inAirMoveHorizontalForce, 0) * EntityMass);
         //steering against moving direction (fast reverse accel)
         else if (isKeyDownLeft == true && currentVelocity.x >= 0)
           SimAddForce(new Vector2(-PhysicsParams.inAirMoveHorizontalForceReverse, 0) * EntityMass);
         else if (isKeyDownRight == true && currentVelocity.x <= 0)
           SimAddForce(new Vector2(PhysicsParams.inAirMoveHorizontalForceReverse, 0) * EntityMass);
       }
 
       //-----------------
       //ON GROUND SIDEWAYS:
       if (isPlayerInAir == false) {
         //steering into moving direction (slow accel)
         if (isKeyDownLeft == true && currentVelocity.x <= 0)
           SimAddForce(new Vector2(-PhysicsParams.onGroundMoveHorizontalForce, 0) * EntityMass);
         else if (isKeyDownRight == true && currentVelocity.x >= 0)
           SimAddForce(new Vector2(PhysicsParams.onGroundMoveHorizontalForce, 0) * EntityMass);
         //steering against moving direction (fast reverse accel)
         else if (isKeyDownLeft == true && currentVelocity.x >= 0)
           SimAddForce(new Vector2(-PhysicsParams.onGroundMoveHorizontalForceReverse, 0) * EntityMass);
         else if (isKeyDownRight == true && currentVelocity.x <= 0)
           SimAddForce(new Vector2(PhysicsParams.onGroundMoveHorizontalForceReverse, 0) * EntityMass);
         //not steering -> brake due to friction.
         else if (isKeyDownLeft != true && isKeyDownRight != true && currentVelocity.x > 0)
           SimAddForce(new Vector2(-PhysicsParams.groundFriction, 0) * EntityMass);
         else if (isKeyDownLeft != true && isKeyDownRight != true && currentVelocity.x < 0)
           SimAddForce(new Vector2(PhysicsParams.groundFriction, 0) * EntityMass);
 
         //in case the velocity is close to 0 and no keys are pressed we should make the the player stop.
         //to do this let's first undo the prior friction force, and then set the velocity to 0.
         if (isKeyDownLeft != true && isKeyDownRight != true && currentVelocity.x > 0 && currentVelocity.x < PhysicsParams.groundFrictionEpsilon) {
           SimAddForce(new Vector2(PhysicsParams.groundFriction, 0) * EntityMass);
           currentVelocity.x = 0;
         } else if (isKeyDownLeft != true && isKeyDownRight != true && currentVelocity.x < 0 && currentVelocity.x > -PhysicsParams.groundFrictionEpsilon) {
           SimAddForce(new Vector2(-PhysicsParams.groundFriction, 0) * EntityMass);
           currentVelocity.x = 0;
         }
       }
     }
 
     public void ResetVelocity() {
       currentVelocity = Vector2.zero;
     }
 
     public void OnCollisionStay2D(Collision2D collision) {
 
       foreach (ContactPoint2D contactPoint in collision.contacts) {
         if (GetIsVectorClose(new Vector2(0, 1), contactPoint.normal)) {
           timeRealLastGroundCollision = Time.realtimeSinceStartup;
           currentVelocity.y = Mathf.Clamp(currentVelocity.y, 0, Mathf.Abs(currentVelocity.y));
         }
         if (GetIsVectorClose(new Vector2(1, 0), contactPoint.normal)) {
           timeRealLastWallLeftCollision = Time.realtimeSinceStartup;
           currentVelocity.x = Mathf.Clamp(currentVelocity.x, 0, Mathf.Abs(currentVelocity.x));
         }
         if (GetIsVectorClose(new Vector2(-1, 0), contactPoint.normal)) {
           timeRealLastWallRightCollision = Time.realtimeSinceStartup;
           currentVelocity.x = Mathf.Clamp(currentVelocity.x, -Mathf.Abs(currentVelocity.x), 0);
         }
         if(GetIsVectorClose(Vector2.down, contactPoint.normal)) {
           currentVelocity.y = Mathf.Clamp(currentVelocity.y, -Mathf.Abs(currentVelocity.y), 0);
         }
       }
     }
 
     private bool GetIsVectorClose(Vector2 vectorA, Vector2 vectorB) {
       return(Mathf.Approximately(0, Vector2.Distance(vectorA, vectorB)));
     }
 
     public void OnLifeChanged (int life, Vector2 contactVector) {
       const float forceEnemyCollision = 15.0f;
       currentVelocity = contactVector.normalized * forceEnemyCollision;
     }
       
     public void ResetPlayer() {
       currentVelocity = Vector2.zero;
     }
   }
 }
 
Comment
Add comment
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 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by tormentoarmagedoom · May 09, 2018 at 08:15 AM

Good day.

If you need help, you need to help us first... Do you think we will read 300 lines of code just for help you ... :D !!

About your question, you want to move the player GameObject in the direction is facing, when mouse click.

Then you need to use following tools/functions. Read them, learn how to use it, and find the solution by your own!

 gameobject.transform.rotation (to know where the player is looking at)    
 
 gameobject.transform.Translate (to move the player)    
 
 if (Input.GetKeyDown(KeyCode.Mouse0))
 {
 }

Using this, you should be able to write your own code!

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 CadenGS_ · May 09, 2018 at 12:50 PM 0
Share

I understand, sorry about the 300 lines lol, I thought you might need a code in case there was conflict, so basically I probably am going to use a completely separate script from my movement, so when I click the souse it dashes so if I’m holding d going right and hot mouse it dashes right

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

189 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 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 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 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 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 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 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

Charecter keeps playing walking animation after punching 0 Answers

Running script isn't working correctly 1 Answer

Please help with infinite gravity swapping problem 0 Answers

How can I get the player to face the direction it is going in a Unity 2D Game?,How do I make it so that my character faces in the direction it is facing in a 2D Unity Game 0 Answers

2D Movement System (Stop Movement on Collision) 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