- Home /
Swinging a sword through code
Hey there!
I'm new to unity, though I'm not new to coding so no worries about that.
Now, what I want to do is to swing my sword through code instead of using animations since I'm horrible at rigging, animating and all that. The only part I need help with is the actual swing.
First I thought I'd parent the object to my player (which is just a cube). Now, how would I swing the sword through a C# script which is attached to the player (the cube)? No need to get super-fancy right now. All I really need to know is how to actually move the sword in the first place.
If you are familiar with transforms and it's properties, you just need to create a transform variable on your script and assign the sword there. From there, you will code your swing. The reason an animation is used is because the movement is normally repeated over and over. You will just end up doing this movement manually with coding.
Answer by TyrusPeace · Aug 06, 2012 at 02:01 AM
Just moving the thing would generally involve calling lerp or slerp on the angle you want your sword to be at when the swing is over and updating it per update:
http://docs.unity3d.com/Documentation/ScriptReference/Vector3.Slerp.html
Slerp could work nicely because you can interpolate it across the surface of a sphere, but personally I'd just use lerp to change the angle of the thing over time in Update() after swinging and set it via eulerAngles:
http://docs.unity3d.com/Documentation/ScriptReference/Vector3.Lerp.html http://docs.unity3d.com/Documentation/ScriptReference/Transform-eulerAngles.html
Well, now I feel dumb because I was so simple. I thought I had to do a bunch of things but nope. Simple enough. I just changed it around and used transform.localPosition ins$$anonymous$$d! Cheers!
Answer by DavidD · Aug 06, 2012 at 11:03 AM
In case anyone else wants the basic code:
swordTransform = transform.FindChild("Sword");
void Update() {
swordTransform.transform.localPosition = Vector3.Slerp(swordTransform.localPosition, new Vector3(1, 0, 1), 0.01f);
}
Answer by Alpha_Guac · Oct 19, 2015 at 10:36 AM
I found that using Vector3.Lerp was more what I wanted than Slerp. I would suggest switching between the two to find what best works for what you want
Your answer
Follow this Question
Related Questions
how do i make a weapon swing like a crowbar or a baseball bat 2 Answers
on collision damage 1 Answer
Swinging a sword without an animation... 1 Answer
RPG Swing attack hit detection 6 Answers
What is the best way to do third person melee combat? 1 Answer