Question by
almustaness · Oct 21, 2017 at 11:22 AM ·
c#animationscripting problem
I spent 6 hours and I failed to launch a ball forward? I could not figure out what is happening?
Hi guys, I am watching this tutorial: youtube
I am trying to fire the ball forward but it fell down directly once it gets out the cannon. This is my code and please tell me if you need more information. By the way I use just a Cylinder instead of the cannon:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cannonController : MonoBehaviour {
public int speed;
public float friction;
public float lerpSpeed;
float xDegrees;
float yDegrees;
Quaternion fromRotation;
Quaternion toRotation;
Camera camera;
public GameObject cannonBall;
Rigidbody cannonballRB;
public Transform shotPos;
public GameObject explosion;
public float firePower;
public int powerMultiplayer = 100;
void Start () {
camera = Camera.main;
firePower *= powerMultiplayer;
}
void Update () {
RaycastHit hit;
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)){
if(hit.transform.gameObject.tag == "Cannon"){
if(Input.GetMouseButton(0)){
xDegrees -= Input.GetAxis("Mouse Y") * speed * friction;
yDegrees += Input.GetAxis("Mouse X") * speed * friction;
fromRotation = transform.rotation;
toRotation = Quaternion.Euler(xDegrees, yDegrees, 0);
transform.rotation = Quaternion.Lerp(fromRotation, toRotation, Time.deltaTime * lerpSpeed);
}
}
}
if(Input.GetMouseButtonDown(1)){
FireCannon();
}
}
public void FireCannon(){
GameObject cannonBallCopy = Instantiate(cannonBall, shotPos.position, transform.rotation) as GameObject;
cannonballRB = cannonBallCopy.GetComponent<Rigidbody>();
cannonballRB.AddForce(transform.forward * firePower);
Instantiate(explosion, shotPos.position, shotPos.rotation);
}
}
Comment
I did with so many different values including what the instructor did. But unfortunately, still the ball keeps falling to down direction. See my settings and please share your answer.
1.png
(373.7 kB)
Answer by Cuttlas-U · Oct 22, 2017 at 05:07 PM
hi; try this :
cannonballRB.AddForce(transform.forward * firePower , ForceMode.Impulse);
give me a screen shot from your canon inspector too;