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 /
avatar image
0
Question by awts202 · Mar 28, 2017 at 06:43 PM · camerarotationdirectionball

How to change direction of ball whenever i rotate my camera around it?

Hello, I'm new to unity and currently working on a game. I'm trying to change the ball's movement to where my camera's direction. If I rotate my camera to the left the ball's movement should go forward to where my camera is facing and left and right should also change.

Here's my code to my player.

public class PlayerController : MonoBehaviour { public float speed = 30; public float maxSpeed = 5;

 void Start()
 {
     rb = GetComponent<Rigidbody>();
 
 }
 
 void FixedUpdate()
 {
     if(Input.GetKey(KeyCode.W))
         {
         rb.AddForce(Vector3.forward * speed, ForceMode.Acceleration);
         transform.position = transform.position + Camera.main.transform.forward * speed * Time.deltaTime;

         }
     if(Input.GetKey(KeyCode.S)){
         rb.AddForce(Vector3.back * speed,ForceMode.Acceleration);
     }
     if(Input.GetKey(KeyCode.A)){
         rb.AddForce(Vector3.left*speed,ForceMode.Acceleration);
          }
     if(Input.GetKey(KeyCode.D))
     {
         rb.AddForce(Vector3.right*speed,ForceMode.Acceleration);
     }
     if (rb.velocity.magnitude > maxSpeed)
     {
         rb.velocity = rb.velocity.normalized * maxSpeed;
     }
 }

Code to camera.

 public GameObject target;
 public float rotateSpeed = 1.0f;
 public float distance = 5.0f;
 public float xSpeed = 2.0f;
 public float ySpeed = 2.0f;
 public float yMinLimit = -90f;
 public float yMaxLimit = 90f;
 public float distanceMin = 10f;
 public float distanceMax = 10f;
 public float smoothTime = 2f;
 float rotationYAxis = 0.0f;
 float rotationXAxis = 0.0f;
 float velocityX = 0.0f;
 float velocityY = 0.0f;
 private Vector3 offset;

 void Start()
 {
     Vector3 angles = transform.eulerAngles;
     rotationYAxis = angles.y;
     rotationXAxis = angles.x;
     offset = transform.position - target.transform.position;
     if (GetComponent<Rigidbody>())
     {
         GetComponent<Rigidbody>().freezeRotation = true;
     }
 }
 
 void Update()
 {
     transform.position = target.transform.position + offset;
 }
 
 void LateUpdate()
 {
     if (target)
     {      
         if (Input.GetMouseButton(0))
         {
             velocityX += xSpeed * Input.GetAxis("Mouse X") * distance * 0.02f;
             velocityY += ySpeed * Input.GetAxis("Mouse Y") * 0.02f;
         }
         rotationYAxis += velocityX;
         rotationXAxis -= velocityY;
         rotationXAxis = ClampAngle(rotationXAxis, yMinLimit, yMaxLimit);
         Quaternion fromRotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, 0);
         Quaternion toRotation = Quaternion.Euler(rotationXAxis, rotationYAxis, 0);
         Quaternion rotation = toRotation;
 
         distance = Mathf.Clamp(distance  *Input.GetAxis("Mouse ScrollWheel") * 5, distanceMin, distanceMax);
 
         Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
         Vector3 position = rotation * negDistance + target.transform.position;
         transform.rotation = rotation;
         transform.position = position;
         transform.LookAt(target.transform);
         velocityX = Mathf.Lerp(velocityX, 0, Time.deltaTime * smoothTime);
         velocityY = Mathf.Lerp(velocityY, 0, Time.deltaTime * smoothTime);
     }
 
 }
 public static float ClampAngle(float angle, float min, float max)
 {
     if (angle < -360F)
         angle += 360F;
     if (angle > 360F)
         angle -= 360F;
     return Mathf.Clamp(angle, min, max);
 }

}

Any help will be appreciated. Thanks.

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
1
Best Answer

Answer by MarshallN · Mar 28, 2017 at 07:05 PM

Currently, you're moving the ball based on world vectors - Vector3.back is always going to be the -z direction in world space, regardless of where the camera is.

You want to do something like

  using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  
  public class PlayerController : MonoBehaviour {
  
      public float speed = 30f;
      public float maxSpeed = 5f;
      private Rigidbody rb;
      public GameObject mainCamera;
  
      // Use this for initialization
      void Start () {
          rb = GetComponent<Rigidbody>();
      }

      void FixedUpdate()
      {
          Vector3 fromCameraToMe = transform.position - mainCamera.transform.position;
          fromCameraToMe.y = 0; // First, zero out any vertical component, so the movement plane is always horizontal.
          fromCameraToMe.Normalize(); // Then, normalize the vector to length 1 so that we don't affect the player more strongly when the camera is at different distances.
          float moveHorizontal = Input.GetAxis("Horizontal");
          float moveVertical = Input.GetAxis("Vertical");
  
          //Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
          // We can cheat a bit here - we had to flatten out the 'forward' vector from the camera to the player, but the camera is always horizontal left-right, so we can just use
          // its 'transform.right' vector to determine the direction to move the ball. Add the horizontal and vertical vectors to determine ground-plane movement.
          Vector3 movement = (fromCameraToMe * moveVertical + mainCamera.transform.right * moveHorizontal) * speed;
  
          rb.AddForce(movement * speed);

          if (rb.velocity.magnitude > maxSpeed)
          {
              rb.velocity = rb.velocity.normalized * maxSpeed;
          }
      }
  }


and then drag the camera GameObject into the 'mainCamera' field in the Inspector view.

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 awts202 · Mar 29, 2017 at 08:01 AM 0
Share

That works really great, in fact I already tried this and your transform.right save me. Thank you so much. I really appreciate your answer.

avatar image MarshallN awts202 · Mar 29, 2017 at 02:10 PM 0
Share

Glad it's working out for you!

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Camera/Direction Rotation 2 Answers

Getting 3rd person to look in direction of camera when right mouse clicked 1 Answer

How do I make a camera follow an object without changing its rotation in C#? 1 Answer

How to change object direction when Camera Rotates 0 Answers

Quaternion.LookRotation is making my object rotate around a point? 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